Skip to content

Commit

Permalink
fix(logging): create log file if it doesn't exist (#3202)
Browse files Browse the repository at this point in the history
  • Loading branch information
phantumcode authored Sep 1, 2023
1 parent c20e64c commit 73db7ad
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ actor LogActor {
}

private func write(_ data: Data) throws {
try rotation.ensureFileExists()
if rotation.currentLogFile.hasSpace(for: data) {
try rotation.currentLogFile.write(data: data)
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,12 @@ final class LogRotation {
index: 0,
fileSizeLimitInBytes: fileSizeLimitInBytes)
}

func ensureFileExists() throws {
if !FileManager.default.fileExists(atPath: currentLogFile.fileURL.relativePath) {
try rotate()
}
}

/// - Returns: A UInt representing the best guess to which index to use
/// next when the number of log files is less that the limit
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,24 @@ final class LogActorTests: XCTestCase {
logs = try await systemUnderTest.getLogs()
XCTAssertEqual(logs.count, 2)
}

/// Given: a Log file
/// When: LogActor writes to a log file that doesn't exist
/// Then: the log file is created and the log entry is recorded
func testLogActorCreatesLogFileIfItDoesNotExist() async throws {
let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)
let fileURL = try XCTUnwrap(files.first)
try FileManager.default.removeItem(at: fileURL)
var logs = try await systemUnderTest.getLogs()
XCTAssertEqual(logs.count, 0)

let entry = LogEntry(category: "LogActorTests", namespace: nil, level: .error, message: UUID().uuidString, created: .init(timeIntervalSince1970: 0))
try await systemUnderTest.record(entry)
try await systemUnderTest.synchronize()

logs = try await systemUnderTest.getLogs()
XCTAssertEqual(logs.count, 1)
let contents = try XCTUnwrap(FileManager.default.contents(atPath: fileURL.path))
XCTAssertNotNil(contents)
}
}

0 comments on commit 73db7ad

Please sign in to comment.