Skip to content

Commit 73db7ad

Browse files
authored
fix(logging): create log file if it doesn't exist (#3202)
1 parent c20e64c commit 73db7ad

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/Persistence/LogActor.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ actor LogActor {
2929
}
3030

3131
private func write(_ data: Data) throws {
32+
try rotation.ensureFileExists()
3233
if rotation.currentLogFile.hasSpace(for: data) {
3334
try rotation.currentLogFile.write(data: data)
3435
} else {

AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/Persistence/LogRotation.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,12 @@ final class LogRotation {
9898
index: 0,
9999
fileSizeLimitInBytes: fileSizeLimitInBytes)
100100
}
101+
102+
func ensureFileExists() throws {
103+
if !FileManager.default.fileExists(atPath: currentLogFile.fileURL.relativePath) {
104+
try rotate()
105+
}
106+
}
101107

102108
/// - Returns: A UInt representing the best guess to which index to use
103109
/// next when the number of log files is less that the limit

AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/LogActorTests.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,4 +127,24 @@ final class LogActorTests: XCTestCase {
127127
logs = try await systemUnderTest.getLogs()
128128
XCTAssertEqual(logs.count, 2)
129129
}
130+
131+
/// Given: a Log file
132+
/// When: LogActor writes to a log file that doesn't exist
133+
/// Then: the log file is created and the log entry is recorded
134+
func testLogActorCreatesLogFileIfItDoesNotExist() async throws {
135+
let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)
136+
let fileURL = try XCTUnwrap(files.first)
137+
try FileManager.default.removeItem(at: fileURL)
138+
var logs = try await systemUnderTest.getLogs()
139+
XCTAssertEqual(logs.count, 0)
140+
141+
let entry = LogEntry(category: "LogActorTests", namespace: nil, level: .error, message: UUID().uuidString, created: .init(timeIntervalSince1970: 0))
142+
try await systemUnderTest.record(entry)
143+
try await systemUnderTest.synchronize()
144+
145+
logs = try await systemUnderTest.getLogs()
146+
XCTAssertEqual(logs.count, 1)
147+
let contents = try XCTUnwrap(FileManager.default.contents(atPath: fileURL.path))
148+
XCTAssertNotNil(contents)
149+
}
130150
}

0 commit comments

Comments
 (0)