import Foundation import UIKit class FileLogger { static let shared = FileLogger() private var fileHandle: FileHandle? private let logURL: URL private let df: DateFormatter = { let f = DateFormatter() f.dateFormat = "HH:mm:ss.SSS" return f }() private init() { let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] logURL = docs.appendingPathComponent("coreml_test.log") if !FileManager.default.fileExists(atPath: logURL.path) { FileManager.default.createFile(atPath: logURL.path, contents: nil) } fileHandle = try? FileHandle(forWritingTo: logURL) fileHandle?.seekToEndOfFile() log("========== NEW SESSION ==========") log("iOS \(UIDevice.current.systemVersion) | \(UIDevice.current.model)") log("Date: \(Date())") } func log(_ message: String) { let ts = df.string(from: Date()) let thread = Thread.isMainThread ? "MAIN" : (Thread.current.name ?? "BG") let line = "[\(ts)][\(thread)] \(message)\n" if let data = line.data(using: .utf8) { fileHandle?.write(data) } print(line, terminator: "") } func getLogURL() -> URL { logURL } func clearLog() { try? "".write(to: logURL, atomically: true, encoding: .utf8) log("========== LOG CLEARED ==========") } deinit { fileHandle?.closeFile() } } func log(_ msg: String) { FileLogger.shared.log(msg) }