Skip to content

Commit

Permalink
Preserve the original extension when rotating files
Browse files Browse the repository at this point in the history
This change allows older files to be treated the same way by the operating system as the most recent log file.

For example, `MyAppLogfile.log` becomes `MyAppLogfile.1.log` when rotated, instead of `MyAppLogfile.log.1`
  • Loading branch information
Emanuel Jarnea committed Aug 16, 2023
1 parent 2391aa4 commit 66bfa26
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions Sources/FileDestination.swift
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ open class FileDestination: BaseDestination {
let fileSize = attr[FileAttributeKey.size] as! UInt64
// Do file rotation
if fileSize > logFileMaxSize {
rotateFile(filePath)
rotateFile(url)
}
} catch {
print("validateSaveFile error: \(error)")
Expand All @@ -124,32 +124,39 @@ open class FileDestination: BaseDestination {
return saveToFile(str: str)
}

private func rotateFile(_ filePath: String) {
private func rotateFile(_ fileUrl: URL) {
let filePath = fileUrl.path
let lastIndex = (logFileAmount-1)
let firstIndex = 1
do {
for index in stride(from: lastIndex, through: firstIndex, by: -1) {
let oldFile = String.init(format: "%@.%d", filePath, index)
let oldFile = makeRotatedFileUrl(fileUrl, index: index).path

if FileManager.default.fileExists(atPath: oldFile) {
if index == lastIndex {
// Delete the last file
try FileManager.default.removeItem(atPath: oldFile)
} else {
// Move the current file to next index
let newFile = String.init(format: "%@.%d", filePath, index+1)
let newFile = makeRotatedFileUrl(fileUrl, index: index + 1).path
try FileManager.default.moveItem(atPath: oldFile, toPath: newFile)
}
}
}

// Finally, move the current file
let newFile = String.init(format: "%@.%d", filePath, firstIndex)
let newFile = makeRotatedFileUrl(fileUrl, index: firstIndex).path
try FileManager.default.moveItem(atPath: filePath, toPath: newFile)
} catch {
print("rotateFile error: \(error)")
}
}

private func makeRotatedFileUrl(_ fileUrl: URL, index: Int) -> URL {
// The index is appended to the file name, to preserve the original extension.
fileUrl.deletingPathExtension()
.appendingPathExtension("\(index).\(fileUrl.pathExtension)")
}

/// appends a string as line to a file.
/// returns boolean about success
Expand Down

0 comments on commit 66bfa26

Please sign in to comment.