Add logging to file

This commit is contained in:
christophhagen 2020-05-22 21:24:12 +02:00
parent 75f40e9c9e
commit 9aaa98a7a2
2 changed files with 27 additions and 1 deletions

View File

@ -16,5 +16,27 @@ private let df: DateFormatter = {
func log(_ message: String, file: String = #file, line: Int = #line) {
let date = df.string(from: Date())
print("[\(date)][\(file.components(separatedBy: "/").last ?? file):\(line)] \(message)")
let m = "[\(date)][\(file.components(separatedBy: "/").last ?? file):\(line)] \(message)"
print(m)
Log.write("\n" + m)
}
enum Log {
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)
}
static func write(_ message: String) {
guard let f = file else {
return
}
f.write(message.data(using: .utf8)!)
}
private static var file: FileHandle?
}

View File

@ -6,6 +6,8 @@ import SQLite
private let baseFolder = URL(fileURLWithPath: "/caps")
private let logFile = baseFolder.appendingPathComponent("logs/server.log").path
private let publicFolder = baseFolder.appendingPathComponent("Public")
private let imageFolder = publicFolder.appendingPathComponent("images")
@ -65,6 +67,8 @@ private func count(of cap: Int) throws -> Int {
/// [Learn More ](https://docs.vapor.codes/3.0/getting-started/structure/#routesswift)
public func routes(_ router: Router) throws {
try Log.set(logFile: logFile)
// Get the name of a cap
router.getCatching("name", Int.parameter) { request -> Data in
let cap = try request.parameters.next(Int.self)