80 lines
3.7 KiB
Swift
80 lines
3.7 KiB
Swift
import Foundation
|
|
|
|
/// Plain-text log at `~/Library/Logs/Helder/helder.log`, written synchronously so a line
|
|
/// survives a crash moments later. Rotates at 2 MB and keeps 3 old files.
|
|
public final class FileLogger: LogSink, @unchecked Sendable {
|
|
public static let maxBytes = 2 * 1024 * 1024
|
|
public static let keep = 3
|
|
|
|
public let fileURL: URL
|
|
public let minimumLevel: LogLevel
|
|
private let directory: URL
|
|
private let lock = NSLock()
|
|
/// Tracked here so the common path needs no stat per line; nil until the first write.
|
|
private var size: Int?
|
|
|
|
public init(directory: URL, minimumLevel: LogLevel = .debug) {
|
|
self.directory = directory
|
|
self.fileURL = directory.appendingPathComponent("helder.log")
|
|
self.minimumLevel = minimumLevel
|
|
}
|
|
|
|
public static var defaultDirectory: URL {
|
|
FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0].appendingPathComponent("Logs/Helder")
|
|
}
|
|
|
|
/// One line per call: ISO timestamp, level, scope, message.
|
|
///
|
|
/// Never throws and never waits on another lock: it is called from failure paths everywhere.
|
|
public func write(level: LogLevel, scope: String, message: String) {
|
|
guard level >= minimumLevel else { return }
|
|
let line = Data(Self.formatLine(level: level, scope: scope, message: message,
|
|
pid: ProcessInfo.processInfo.processIdentifier, date: Date()).utf8)
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
if size == nil {
|
|
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
size = (try? FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? Int) ?? 0
|
|
}
|
|
if (size ?? 0) + line.count > Self.maxBytes { rotate() }
|
|
// O_APPEND keeps lines from sibling Helder processes sharing this file whole.
|
|
let fd = open(fileURL.path, O_WRONLY | O_APPEND | O_CREAT, 0o644)
|
|
guard fd >= 0 else { return }
|
|
defer { close(fd) }
|
|
let written = line.withUnsafeBytes { Darwin.write(fd, $0.baseAddress, $0.count) }
|
|
if written > 0 { size = (size ?? 0) + written }
|
|
}
|
|
|
|
/// `helder.log` becomes `helder.1.log`, and so on; the oldest beyond `keep` is dropped.
|
|
/// Another process may rotate first, so every step is best effort.
|
|
private func rotate() {
|
|
let fm = FileManager.default
|
|
func old(_ n: Int) -> String { directory.appendingPathComponent("helder.\(n).log").path }
|
|
try? fm.removeItem(atPath: old(Self.keep))
|
|
for n in stride(from: Self.keep - 1, through: 1, by: -1) {
|
|
Darwin.rename(old(n), old(n + 1))
|
|
}
|
|
Darwin.rename(fileURL.path, old(1))
|
|
size = 0
|
|
}
|
|
|
|
/// `2026-07-15T10:00:00.000Z INFO 42 git loaded`; continuation lines are indented
|
|
/// so a message with newlines never looks like a second entry.
|
|
public static func formatLine(level: LogLevel, scope: String, message: String, pid: Int32, date: Date) -> String {
|
|
let stamp = timestampFormatter.string(from: date)
|
|
let indented = message.replacingOccurrences(of: "\r?\n", with: "\n ", options: .regularExpression)
|
|
return "\(stamp) \(pad(level.rawValue.uppercased(), 5)) \(pad(String(pid), 5, left: true)) \(pad(scope, 9)) \(indented)\n"
|
|
}
|
|
|
|
private static func pad(_ text: String, _ width: Int, left: Bool = false) -> String {
|
|
let fill = String(repeating: " ", count: max(0, width - text.count))
|
|
return left ? fill + text : text + fill
|
|
}
|
|
|
|
private static let timestampFormatter: ISO8601DateFormatter = {
|
|
let formatter = ISO8601DateFormatter()
|
|
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
return formatter
|
|
}()
|
|
}
|