OSLog.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. //
  2. // OSLog.swift
  3. // Loop
  4. //
  5. // Copyright © 2017 LoopKit Authors. All rights reserved.
  6. //
  7. //
  8. // OSLog.swift
  9. // OmniBLE
  10. //
  11. // Copyright © 2017 LoopKit Authors. All rights reserved.
  12. // OSLog updated for FreeAPSX logs
  13. //
  14. import os.log
  15. import Foundation
  16. let storeLoopLog: Bool = false
  17. let loggerLock = NSRecursiveLock()
  18. let baseReporter: IssueReporter = SimpleLogReporter()
  19. let category = Logger.Category.loopKit
  20. extension NSLocking {
  21. func perform<T>(_ block: () throws -> T) rethrows -> T {
  22. lock()
  23. defer { unlock() }
  24. return try block()
  25. }
  26. }
  27. extension NSRecursiveLock {
  28. convenience init(label: String) {
  29. self.init()
  30. name = label
  31. }
  32. }
  33. extension NSLock {
  34. convenience init(label: String) {
  35. self.init()
  36. name = label
  37. }
  38. }
  39. extension OSLog {
  40. convenience init(category: String) {
  41. self.init(subsystem: "com.loopkit.LoopKit", category: category)
  42. }
  43. func debug(_ message: StaticString, _ args: CVarArg...) {
  44. if (!storeLoopLog) {
  45. log(message, type: .debug, args)
  46. } else {
  47. let msg_format = message.withUTF8Buffer{
  48. String(decoding: $0, as: UTF8.self)
  49. }
  50. let msg = String(format: msg_format.replacingOccurrences(of: "{public}", with: ""), args)
  51. DispatchWorkItem(qos: .background, flags: .enforceQoS) {
  52. loggerLock.perform {
  53. category.logger.debug(
  54. {msg}(),
  55. printToConsole: true,
  56. file: #file,
  57. function: #function,
  58. line: #line
  59. )
  60. }
  61. }.perform()
  62. }
  63. }
  64. func info(_ message: StaticString, _ args: CVarArg...) {
  65. if (!storeLoopLog) {
  66. log(message, type: .info, args)
  67. } else {
  68. let msg_format = message.withUTF8Buffer{
  69. String(decoding: $0, as: UTF8.self)
  70. }
  71. let msg = String(format: msg_format.replacingOccurrences(of: "{public}", with: ""), args)
  72. DispatchWorkItem(qos: .background, flags: .enforceQoS) {
  73. loggerLock.perform {
  74. category.logger.info(
  75. {msg}(),
  76. file: #file,
  77. function: #function,
  78. line: #line
  79. )
  80. }
  81. }.perform()
  82. }
  83. }
  84. func `default`(_ message: StaticString, _ args: CVarArg...) {
  85. if (!storeLoopLog) {
  86. log(message, type: .default, args)
  87. } else {
  88. let msg_format = message.withUTF8Buffer{
  89. String(decoding: $0, as: UTF8.self)
  90. }
  91. let msg = String(format: msg_format.replacingOccurrences(of: "{public}", with: ""), args)
  92. DispatchWorkItem(qos: .background, flags: .enforceQoS) {
  93. loggerLock.perform {
  94. category.logger.debug(
  95. {msg}(),
  96. printToConsole: true,
  97. file: #file,
  98. function: #function,
  99. line: #line
  100. )
  101. }
  102. }.perform()
  103. }
  104. }
  105. func error(_ message: StaticString, _ args: CVarArg...) {
  106. if (!storeLoopLog) {
  107. log(message, type: .error, args)
  108. } else {
  109. let msg_format = message.withUTF8Buffer{
  110. String(decoding: $0, as: UTF8.self)
  111. }
  112. let msg = String(format: msg_format.replacingOccurrences(of: "{public}", with: ""), args)
  113. DispatchWorkItem(qos: .background, flags: .enforceQoS) {
  114. loggerLock.perform {
  115. category.logger.warning(
  116. {msg}(),
  117. description: {msg}(),
  118. error: nil,
  119. file: #file,
  120. function: #function,
  121. line: #line
  122. )
  123. }
  124. }.perform()
  125. }
  126. }
  127. private func log(_ message: StaticString, type: OSLogType, _ args: [CVarArg]) {
  128. switch args.count {
  129. case 0:
  130. os_log(message, log: self, type: type)
  131. case 1:
  132. os_log(message, log: self, type: type, args[0])
  133. case 2:
  134. os_log(message, log: self, type: type, args[0], args[1])
  135. case 3:
  136. os_log(message, log: self, type: type, args[0], args[1], args[2])
  137. case 4:
  138. os_log(message, log: self, type: type, args[0], args[1], args[2], args[3])
  139. case 5:
  140. os_log(message, log: self, type: type, args[0], args[1], args[2], args[3], args[4])
  141. default:
  142. os_log(message, log: self, type: type, args)
  143. }
  144. }
  145. }
  146. protocol IssueReporter: AnyObject {
  147. /// Call this method in `applicationDidFinishLaunching()`.
  148. func setup()
  149. func setUserIdentifier(_: String?)
  150. func reportNonFatalIssue(withName: String, attributes: [String: String])
  151. func reportNonFatalIssue(withError: NSError)
  152. func log(_ category: String, _ message: String, file: String, function: String, line: UInt)
  153. }
  154. final class Logger {
  155. static let `default` = Logger(category: .default, reporter: baseReporter)
  156. static let loopKit = Logger(category: .loopKit, reporter: baseReporter)
  157. enum Category: String {
  158. case `default`
  159. case loopKit
  160. var name: String {
  161. rawValue
  162. }
  163. var logger: Logger {
  164. switch self {
  165. case .default: return .default
  166. case .loopKit: return .loopKit
  167. }
  168. }
  169. fileprivate var log: OSLog {
  170. let subsystem = Bundle.main.bundleIdentifier!
  171. switch self {
  172. case .default: return OSLog.default
  173. case .loopKit: return OSLog(subsystem: subsystem, category: name)
  174. }
  175. }
  176. }
  177. fileprivate enum Error: Swift.Error {
  178. case error(String)
  179. case errorWithInnerError(String, Swift.Error)
  180. case errorWithDescription(String, String)
  181. case errorWithDescriptionAndInnerError(String, String, Swift.Error)
  182. private func domain() -> String {
  183. switch self {
  184. case let .error(domain),
  185. let .errorWithDescription(domain, _),
  186. let .errorWithDescriptionAndInnerError(domain, _, _),
  187. let .errorWithInnerError(domain, _):
  188. return domain
  189. }
  190. }
  191. private func innerError() -> Swift.Error? {
  192. switch self {
  193. case let .errorWithDescriptionAndInnerError(_, _, error),
  194. let .errorWithInnerError(_, error):
  195. return error
  196. default: return nil
  197. }
  198. }
  199. func asNSError() -> NSError {
  200. var info: [String: Any] = ["Description": String(describing: self)]
  201. if let error = innerError() {
  202. info["Error"] = String(describing: error)
  203. }
  204. return NSError(domain: domain(), code: -1, userInfo: info)
  205. }
  206. }
  207. private let category: Category
  208. private let reporter: IssueReporter
  209. let log: OSLog
  210. private init(category: Category, reporter: IssueReporter) {
  211. self.category = category
  212. self.reporter = reporter
  213. log = category.log
  214. }
  215. static func setup() {
  216. loggerLock.perform {
  217. baseReporter.setup()
  218. }
  219. }
  220. func debug(
  221. _ message: @autoclosure () -> String,
  222. printToConsole: Bool = true,
  223. file: String = #file,
  224. function: String = #function,
  225. line: UInt = #line
  226. ) {
  227. let message = "DEV: \(message())"
  228. if printToConsole {
  229. os_log("%@ - %@ - %d %{public}@", log: log, type: .debug, file.file, function, line, message)
  230. }
  231. reporter.log(category.name, message, file: file, function: function, line: line)
  232. }
  233. func info(
  234. _ message: String,
  235. file: String = #file,
  236. function: String = #function,
  237. line: UInt = #line
  238. ) {
  239. let printedMessage = "INFO: \(message)"
  240. os_log("%@ - %@ - %d %{public}@", log: log, type: .info, file.file, function, line, printedMessage)
  241. reporter.log(category.name, printedMessage, file: file, function: function, line: line)
  242. }
  243. func warning(
  244. _ message: String,
  245. description: String? = nil,
  246. error maybeError: Swift.Error? = nil,
  247. file: String = #file,
  248. function: String = #function,
  249. line: UInt = #line
  250. ) {
  251. let loggerError = maybeError.loggerError(message: message, withDescription: description)
  252. let message = "WARN: \(String(describing: loggerError))"
  253. os_log("%@ - %@ - %d %{public}@", log: log, type: .default, file.file, function, line, message)
  254. reporter.log(category.name, message, file: file, function: function, line: line)
  255. reporter.reportNonFatalIssue(withError: loggerError.asNSError())
  256. }
  257. func error(
  258. _ message: String,
  259. description: String? = nil,
  260. error maybeError: Swift.Error? = nil,
  261. file: String = #file,
  262. function: String = #function,
  263. line: UInt = #line
  264. ) -> Never {
  265. errorWithoutFatalError(message, description: description, error: maybeError, file: file, function: function, line: line)
  266. fatalError(
  267. "\(message) @ \(String(describing: description)) @ \(String(describing: maybeError)) @ \(file) @ \(function) @ \(line)"
  268. )
  269. }
  270. fileprivate func errorWithoutFatalError(
  271. _ message: String,
  272. description: String? = nil,
  273. error maybeError: Swift.Error? = nil,
  274. file: String = #file,
  275. function: String = #function,
  276. line: UInt = #line
  277. ) {
  278. let loggerError = maybeError.loggerError(message: message, withDescription: description)
  279. let message = "ERR: \(String(describing: loggerError))"
  280. os_log("%@ - %@ - %d %{public}@", log: log, type: .error, file.file, function, line, message)
  281. reporter.log(category.name, message, file: file, function: function, line: line)
  282. reporter.reportNonFatalIssue(withError: loggerError.asNSError())
  283. }
  284. }
  285. private extension Optional where Wrapped == Swift.Error {
  286. func loggerError(message: String, withDescription description: String?) -> Logger.Error {
  287. switch (description, self) {
  288. case (nil, nil):
  289. return .error(message)
  290. case let (descr?, nil):
  291. return .errorWithDescription(message, descr)
  292. case let (nil, error?):
  293. return .errorWithInnerError(message, error)
  294. case let (descr?, error?):
  295. return .errorWithDescriptionAndInnerError(message, descr, error)
  296. }
  297. }
  298. }
  299. final class SimpleLogReporter: IssueReporter {
  300. private let fileManager = FileManager.default
  301. private var dateFormatter: DateFormatter {
  302. let dateFormatter = DateFormatter()
  303. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
  304. return dateFormatter
  305. }
  306. func setup() {}
  307. func setUserIdentifier(_: String?) {}
  308. func reportNonFatalIssue(withName _: String, attributes _: [String: String]) {}
  309. func reportNonFatalIssue(withError _: NSError) {}
  310. func log(_ category: String, _ message: String, file: String, function: String, line: UInt) {
  311. let now = Date()
  312. let startOfDay = Calendar.current.startOfDay(for: now)
  313. if !fileManager.fileExists(atPath: SimpleLogReporter.logDir) {
  314. try? fileManager.createDirectory(
  315. atPath: SimpleLogReporter.logDir,
  316. withIntermediateDirectories: false,
  317. attributes: nil
  318. )
  319. }
  320. if !fileManager.fileExists(atPath: SimpleLogReporter.logFile) {
  321. createFile(at: startOfDay)
  322. } else {
  323. if let attributes = try? fileManager.attributesOfItem(atPath: SimpleLogReporter.logFile),
  324. let creationDate = attributes[.creationDate] as? Date, creationDate < startOfDay
  325. {
  326. try? fileManager.removeItem(atPath: SimpleLogReporter.logFilePrev)
  327. try? fileManager.moveItem(atPath: SimpleLogReporter.logFile, toPath: SimpleLogReporter.logFilePrev)
  328. createFile(at: startOfDay)
  329. }
  330. }
  331. let logEntry = "\(dateFormatter.string(from: now)) [\(category)] \(file.file) - \(function) - \(line) - \(message)\n"
  332. let data = logEntry.data(using: .utf8)!
  333. try? data.append(fileURL: URL(fileURLWithPath: SimpleLogReporter.logFile))
  334. }
  335. private func createFile(at date: Date) {
  336. fileManager.createFile(atPath: SimpleLogReporter.logFile, contents: nil, attributes: [.creationDate: date])
  337. }
  338. static var logFile: String {
  339. getDocumentsDirectory().appendingPathComponent("logs/log.txt").path
  340. }
  341. static var logDir: String {
  342. getDocumentsDirectory().appendingPathComponent("logs").path
  343. }
  344. static var logFilePrev: String {
  345. getDocumentsDirectory().appendingPathComponent("logs/log_prev.txt").path
  346. }
  347. static func getDocumentsDirectory() -> URL {
  348. let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
  349. let documentsDirectory = paths[0]
  350. return documentsDirectory
  351. }
  352. }
  353. private extension Data {
  354. func append(fileURL: URL) throws {
  355. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  356. defer {
  357. fileHandle.closeFile()
  358. }
  359. fileHandle.seekToEndOfFile()
  360. fileHandle.write(self)
  361. } else {
  362. try write(to: fileURL, options: .atomic)
  363. }
  364. }
  365. }
  366. private extension String {
  367. var file: String { components(separatedBy: "/").last ?? "" }
  368. }