OSDN Git Service

staticプロパティをインスタンスプロパティに変更
[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 }
58
59 private extension Logger {
60     
61     func stringRepresentation(_ message: String, function: String, file: String, line: Int) -> String {
62         
63         let dateString = dateFormatter.string(from: Date())
64         
65         let file = URL(fileURLWithPath: file).lastPathComponent
66         
67         return "\(dateString) [\(file):\(line)] \(function): \(message)\n"
68     }
69     
70     func printToConsole(_ logMessage: String) {
71         
72         print(logMessage)
73     }
74     
75     func printToDestination(_ logMessage: String) {
76         
77         if let data = logMessage.data(using: .utf8) {
78             
79             fileHandle?.write(data)
80             
81         } else {
82             
83             print("Could not encode logged string into data.")
84         }
85     }
86 }