OSDN Git Service

洋上補給の補強増設用のショートネームをつけた
[kcd/KCD.git] / KCD / Logger.swift
1 //
2 //  Logger.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/10/28.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Foundation
10
11 final class Logger {
12     
13     let destination: URL
14     
15     lazy private var dateFormatter: DateFormatter = {
16         
17         let formatter = DateFormatter()
18         formatter.locale = Locale.current
19         formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
20         
21         return formatter
22     }()
23     
24     lazy private var fileHandle: FileHandle? = {
25         
26         FileManager.default.createFile(atPath: destination.path, contents: nil, attributes: nil)
27         
28         do {
29             
30             return try FileHandle(forWritingTo: destination)
31             
32         } catch {
33             
34             print("Could not open path to log file. \(error).")
35         }
36         
37         return nil
38     }()
39     
40     init(destination: URL) {
41         
42         self.destination = destination
43     }
44     
45     deinit {
46         
47         fileHandle?.closeFile()
48     }
49     
50     func log(_ message: String, function: String = #function, file: String = #file, line: Int = #line) {
51         
52         let logMessage = stringRepresentation(message, function: function, file: file, line: line)
53         
54         printToConsole(logMessage)
55         printToDestination(logMessage)
56     }
57     func log<T>(_ message: String, value: T, function: String = #function, file: String = #file, line: Int = #line) -> T {
58         
59         log(message, function: function, file: file, line: line)
60         
61         return value
62     }
63 }
64
65 private extension Logger {
66     
67     func stringRepresentation(_ message: String, function: String, file: String, line: Int) -> String {
68         
69         let dateString = dateFormatter.string(from: Date())
70         
71         let file = URL(fileURLWithPath: file).lastPathComponent
72         
73         return "\(dateString) [\(file):\(line)] \(function): \(message)\n"
74     }
75     
76     func printToConsole(_ logMessage: String) {
77         
78         print(logMessage)
79     }
80     
81     func printToDestination(_ logMessage: String) {
82         
83         if let data = logMessage.data(using: .utf8) {
84             
85             fileHandle?.write(data)
86             
87         } else {
88             
89             print("Could not encode logged string into data.")
90         }
91     }
92 }