Logger template for iOS12+

Updated
Sep 28, 2022 3:30 PM
Created
Oct 20, 2021 5:13 AM
Tags
Swift
Attributes

Rev3

enum Log {

  static func debug(
    file: StaticString = #file,
    line: UInt = #line,
    _ log: OSLog,
    _ object: @autoclosure () -> Any
  ) {
    os_log(.default, log: log, "%{public}@\n%{public}@:%{public}@", "\(object())", "\(file)", "\(line.description)")
  }

  static func error(
    file: StaticString = #file,
    line: UInt = #line,
    _ log: OSLog,
    _ object: @autoclosure () -> Any
  ) {
    os_log(.error, log: log, "%{public}@\n%{public}@:%{public}@", "\(object())", "\(file)", "\(line.description)")
  }

}

extension OSLog {
  
  @inline(__always)
  private static func makeOSLogInDebug(isEnabled: Bool = true, _ factory: () -> OSLog) -> OSLog {
#if DEBUG
    return factory()
#else
    return .disabled
#endif
  }
  
  static let `default`: OSLog = makeOSLogInDebug { OSLog.init(subsystem: "", category: "") }
}

Rev2

enum Log {

  static func debug(_ log: OSLog, _ object: Any...) {
    os_log(.debug, log: log, "%@", object.map { "\($0)" }.joined(separator: " "))
  }

  static func error(_ log: OSLog, _ object: Any...) {
    os_log(.error, log: log, "%@", object.map { "\($0)" }.joined(separator: " "))
  }

}

extension OSLog {

  @inline(__always)
  private static func makeOSLogInDebug(_ factory: () -> OSLog) -> OSLog {
    #if DEBUG
    return factory()
    #else
    return .disabled
    #endif
  }

  static let capture: OSLog = makeOSLogInDebug { OSLog.init(subsystem: "Capturer", category: "πŸ“Έ Capture") }

  static let orientation: OSLog = makeOSLogInDebug { OSLog.init(subsystem: "Capturer", category: "πŸ€ΈπŸ»β€β™‚οΈ Orientation") }
}

Rev1

enum Log {

    private static let log = OSLog.init(subsystem: <#subsystem#>, category: <#category#>)

    static func debug(_ object: Any...) {
      os_log(.debug, log: log, "%@", object.map { "\($0)" }.joined(separator: " "))
    }

  }