Logging functionality (#71)

Enhancing logging functionality, including log format options
This commit is contained in:
Michael Mock authored and GitHub committed 2025-07-05 09:29:41 +02:00
1 parent bf012927b4
commit a4e4b6027d
7 files changed
+238 -60

No files matched your search

+65 -3
View File
@@ -8,6 +8,11 @@
import Foundation
import MP42Foundation
enum LogFormat: Int {
case timeOnly = 0
case dateAndTime = 1
}
final class Logger : NSObject, MP42Logging {
var delegate: MP42Logging?
@@ -15,7 +20,14 @@ final class Logger : NSObject, MP42Logging {
private let fileURL: URL
private let queue: DispatchQueue
init(fileURL: URL) {
private var format: LogFormat {
get {
let logPref: Int = Prefs.logFormat
return LogFormat(rawValue: logPref) ?? .timeOnly
}
}
init(fileURL: URL, format: LogFormat = Logger.defaultFormat()) {
self.fileURL = fileURL
self.queue = DispatchQueue(label: "org.subler.LogQueue")
}
@@ -24,7 +36,17 @@ final class Logger : NSObject, MP42Logging {
var currentTime = time(nil)
if let localTime = localtime(&currentTime) {
let p = localTime.pointee
return "\(p.tm_hour):\(p.tm_min):\(p.tm_sec)"
return String(format: "%02d:%02d:%02d", p.tm_hour, p.tm_min, p.tm_sec)
} else {
return ""
}
}
private func currentDate() -> String {
var currentTime = time(nil)
if let localTime = localtime(&currentTime) {
let p = localTime.pointee
return String(format: "%04d-%02d-%02d", p.tm_year + 1900, p.tm_mon + 1, p.tm_mday)
} else {
return ""
}
@@ -32,7 +54,14 @@ final class Logger : NSObject, MP42Logging {
func write(toLog string: String) {
queue.sync {
let output = "\(currentTime()) \(string)\n"
let prefix: String
switch format {
case .timeOnly:
prefix = currentTime()
case .dateAndTime:
prefix = "\(currentDate()) \(currentTime())"
}
let output = "\(prefix) \(string)\n"
fileURL.withUnsafeFileSystemRepresentation {
if let file = fopen($0, "a") {
@@ -55,5 +84,38 @@ final class Logger : NSObject, MP42Logging {
try? FileManager.default.removeItem(at: fileURL)
}
static func defaultFormat() -> LogFormat {
let logPref: Int = Prefs.logFormat
return LogFormat(rawValue: logPref) ?? .timeOnly
}
static func makeDefault() -> Logger {
Logger(fileURL: defaultLogFile)
}
static var defaultLogFile: URL = {
let url = defaultDirectoryURL().appendingPathComponent("debugLog.txt")
return url
}()
static func defaultDirectoryURL() -> URL {
let fileManager = FileManager.default
if let url = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask)
.first?.appendingPathComponent("Subler") {
do {
if fileManager.fileExists(atPath: url.path) == false {
try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: [:])
}
}
catch _ {
fatalError("Couldn't create the app support directory")
}
return url
}
else {
fatalError("Couldn't find the app support directory")
}
}
}