Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New FileHandle for each log write #81

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions TomatoBar/Log.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,15 @@ private let lineEnd = "\n".data(using: .utf8)!
internal let logger = TBLogger()

class TBLogger {
private let logHandle: FileHandle?
private let encoder = JSONEncoder()

init() {
encoder.outputFormatting = .sortedKeys
encoder.dateEncodingStrategy = .secondsSince1970

}

func openFileHandle() -> FileHandle? {
let logHandle: FileHandle?
let fileManager = FileManager.default
let logPath = fileManager
.urls(for: .cachesDirectory, in: .userDomainMask)
Expand All @@ -50,21 +52,25 @@ class TBLogger {
guard fileManager.createFile(atPath: logPath, contents: nil) else {
print("cannot create log file")
logHandle = nil
return
return nil
}
}

logHandle = FileHandle(forUpdatingAtPath: logPath)
guard logHandle != nil else {
print("cannot open log file")
return
return nil
}

return logHandle
}

func append(event: TBLogEvent) {
let logHandle = openFileHandle()
guard let logHandle = logHandle else {
return
}

do {
let jsonData = try encoder.encode(event)
try logHandle.seekToEnd()
Expand Down