5 // Created by Hori,Masaki on 2017/10/28.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
15 lazy private var dateFormatter: DateFormatter = {
17 let formatter = DateFormatter()
18 formatter.locale = Locale.current
19 formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
24 lazy private var fileHandle: FileHandle? = {
26 FileManager.default.createFile(atPath: destination.path, contents: nil, attributes: nil)
30 return try FileHandle(forWritingTo: destination)
34 print("Could not open path to log file. \(error).")
40 init(destination: URL) {
42 self.destination = destination
47 fileHandle?.closeFile()
50 func log(_ message: String, function: String = #function, file: String = #file, line: Int = #line) {
52 let logMessage = stringRepresentation(message, function: function, file: file, line: line)
54 printToConsole(logMessage)
55 printToDestination(logMessage)
57 func log<T>(_ message: String, value: T, function: String = #function, file: String = #file, line: Int = #line) -> T {
59 log(message, function: function, file: file, line: line)
65 private extension Logger {
67 func stringRepresentation(_ message: String, function: String, file: String, line: Int) -> String {
69 let dateString = dateFormatter.string(from: Date())
71 let file = URL(fileURLWithPath: file).lastPathComponent
73 return "\(dateString) [\(file):\(line)] \(function): \(message)\n"
76 func printToConsole(_ logMessage: String) {
81 func printToDestination(_ logMessage: String) {
83 if let data = logMessage.data(using: .utf8) {
85 fileHandle?.write(data)
89 print("Could not encode logged string into data.")