Caps-Server/Sources/App/Log.swift

49 lines
1.3 KiB
Swift
Raw Normal View History

2020-05-19 15:19:19 +02:00
//
// Log.swift
// App
//
// Created by Christoph on 05.05.20.
//
import Foundation
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())
2020-05-22 21:24:12 +02:00
let m = "[\(date)][\(file.components(separatedBy: "/").last ?? file):\(line)] \(message)"
print(m)
2020-05-23 14:54:27 +02:00
Log.write(m + "\n")
2020-05-22 21:24:12 +02:00
}
enum Log {
static func set(logFile: String) throws {
let url = URL(fileURLWithPath: logFile)
2020-05-23 14:54:27 +02:00
let date = df.string(from: Date())
2020-05-22 21:24:12 +02:00
if !FileManager.default.fileExists(atPath: logFile) {
2020-05-23 14:54:27 +02:00
try "[\(date)] New log created.\n".write(to: url, atomically: false, encoding: .utf8)
2020-05-22 21:24:12 +02:00
}
2020-05-23 14:54:27 +02:00
guard let f = FileHandle(forWritingAtPath: logFile) else {
try "[\(date)] Failed to start log.\n".write(to: url, atomically: false, encoding: .utf8)
return
}
file?.write("[\(date)] Logging started.\n".data(using: .utf8)!)
file = f
2020-05-22 21:24:12 +02:00
}
static func write(_ message: String) {
guard let f = file else {
return
}
f.write(message.data(using: .utf8)!)
}
private static var file: FileHandle?
2020-05-19 15:19:19 +02:00
}