Log.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import Foundation
  2. struct Log {
  3. private static let dateFormat = "yy-MM-dd hh:mm:ss.SSS"
  4. private static let dateFormatter: DateFormatter = {
  5. let formatter = DateFormatter()
  6. formatter.dateFormat = dateFormat
  7. formatter.locale = .current
  8. formatter.timeZone = .current
  9. return formatter
  10. }()
  11. static func d(_ tag: String, _ message: String, _ other: Any?...) {
  12. log(.debug, tag, message, other)
  13. }
  14. static func i(_ tag: String, _ message: String, _ other: Any?...) {
  15. log(.info, tag, message, other)
  16. }
  17. static func w(_ tag: String, _ message: String, _ other: Any?...) {
  18. log(.warning, tag, message, other)
  19. }
  20. static func e(_ tag: String, _ message: String, _ other: Any?...) {
  21. log(.error, tag, message, other)
  22. }
  23. private static func log(_ level: LogLevel, _ tag: String, _ message: String, _ other: Any?...) {
  24. print("\(dateStr()) ntfyApp [\(levelStr(level))] \(tag): \(message)")
  25. if !other.isEmpty {
  26. other.forEach { o in
  27. if let o = o {
  28. print(" ", o)
  29. }
  30. }
  31. }
  32. }
  33. private static func dateStr() -> String {
  34. dateFormatter.string(from: Date())
  35. }
  36. private static func levelStr(_ level: LogLevel) -> String {
  37. switch level {
  38. case .debug: return "DEBUG"
  39. case .info: return "INFO"
  40. case .warning: return "WARNING ⚠️"
  41. case .error: return "ERROR ‼️"
  42. }
  43. }
  44. }
  45. private enum LogLevel {
  46. case debug
  47. case info
  48. case warning
  49. case error
  50. }