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)
59 private extension Logger {
61 func stringRepresentation(_ message: String, function: String, file: String, line: Int) -> String {
63 let dateString = dateFormatter.string(from: Date())
65 let file = URL(fileURLWithPath: file).lastPathComponent
67 return "\(dateString) [\(file):\(line)] \(function): \(message)\n"
70 func printToConsole(_ logMessage: String) {
75 func printToDestination(_ logMessage: String) {
77 if let data = logMessage.data(using: .utf8) {
79 fileHandle?.write(data)
83 print("Could not encode logged string into data.")