2019-03-15 13:19:19 +01:00
|
|
|
import Foundation
|
|
|
|
|
|
|
|
protocol Logger {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2020-06-18 22:55:51 +02:00
|
|
|
private let df: DateFormatter = {
|
|
|
|
let df = DateFormatter()
|
|
|
|
df.dateStyle = .short
|
|
|
|
df.timeStyle = .short
|
|
|
|
return df
|
|
|
|
}()
|
|
|
|
|
|
|
|
func log(_ message: String, file: String = #file, line: Int = #line) {
|
|
|
|
let date = df.string(from: Date())
|
|
|
|
let m = "[\(date)][\(file.components(separatedBy: "/").last ?? file):\(line)] \(message)"
|
|
|
|
print(m)
|
|
|
|
Log.write(m + "\n")
|
|
|
|
}
|
|
|
|
|
2019-03-15 13:19:19 +01:00
|
|
|
extension Logger {
|
2022-06-10 21:20:49 +02:00
|
|
|
|
2020-05-16 11:21:55 +02:00
|
|
|
static var logToken: String {
|
|
|
|
"[" + String(describing: self) + "] "
|
|
|
|
}
|
2019-03-15 13:19:19 +01:00
|
|
|
|
|
|
|
func error(_ message: String) {
|
2020-05-16 11:21:55 +02:00
|
|
|
Self.addToFile(Self.logToken + "ERROR: " + message)
|
2019-03-15 13:19:19 +01:00
|
|
|
}
|
|
|
|
|
2020-05-16 11:21:55 +02:00
|
|
|
func log(_ message: String) {
|
|
|
|
Self.addToFile(Self.logToken + message)
|
2019-03-15 13:19:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
static func error(_ message: String) {
|
2020-05-16 11:21:55 +02:00
|
|
|
addToFile(logToken + "ERROR: " + message)
|
2019-03-15 13:19:19 +01:00
|
|
|
}
|
|
|
|
|
2020-05-16 11:21:55 +02:00
|
|
|
static func log(_ message: String) {
|
|
|
|
addToFile(logToken + message)
|
2019-04-12 13:45:31 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
2019-04-12 13:45:31 +02:00
|
|
|
private static func addToFile(_ message: String) {
|
2020-06-18 22:55:51 +02:00
|
|
|
Log.write("\n" + message)
|
2019-04-12 13:45:31 +02:00
|
|
|
print(message)
|
2019-03-15 13:19:19 +01:00
|
|
|
}
|
|
|
|
}
|
2019-04-12 13:45:31 +02:00
|
|
|
|
2020-06-18 22:55:51 +02:00
|
|
|
enum Log {
|
2022-06-10 21:20:49 +02:00
|
|
|
|
2020-06-18 22:55:51 +02:00
|
|
|
static func set(logFile: String) throws {
|
|
|
|
let url = URL(fileURLWithPath: logFile)
|
|
|
|
if !FileManager.default.fileExists(atPath: logFile) {
|
|
|
|
try "Log started".write(to: url, atomically: false, encoding: .utf8)
|
|
|
|
}
|
|
|
|
file = FileHandle(forWritingAtPath: logFile)
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
2020-06-18 22:55:51 +02:00
|
|
|
static func write(_ message: String) {
|
|
|
|
guard let f = file else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
f.write(message.data(using: .utf8)!)
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
2020-06-18 22:55:51 +02:00
|
|
|
private static var file: FileHandle?
|
|
|
|
}
|
2019-04-12 13:45:31 +02:00
|
|
|
|