Skip to content

Instantly share code, notes, and snippets.

@chockenberry
Last active April 11, 2024 13:22
Show Gist options
  • Save chockenberry/3b5b14ce2186f62d60eec4afea986bb2 to your computer and use it in GitHub Desktop.
Save chockenberry/3b5b14ce2186f62d60eec4afea986bb2 to your computer and use it in GitHub Desktop.
Debug and release logging in Swift that's reminiscent of NSLog()
//
// Debug.swift
//
// Created by Craig Hockenberry on 3/15/17.
// Updated by Craig Hockenberry on 2/20/24.
// Usage:
//
// SplineReticulationManager.swift:
//
// func reticulationFunction() -> Float {
// debugLog() // prints "SplineReticulationManager: reticulationFunction() called"
//
// let splineCount = Int.random(in: 0...2000)
// debugLog("reticulating \(splineCount) splines" // prints "SplineReticulationManager: reticulationFunction() reticulating 1337 splines"
//
// return debugResult(Float.random(in: 0...1)) // prints "SplineReticulationManager: reticulationFunction() returned: 5.8008"
// }
import Foundation
import OSLog
let defaultLogger = Logger()
public func releaseLog(_ message: String = "called", file: String = #file, function: String = #function) {
defaultLogger.info("\(URL(fileURLWithPath: file, isDirectory: false).deletingPathExtension().lastPathComponent): \(function) \(message)")
}
public func debugLog(_ message: String = "called", file: String = #file, function: String = #function) {
#if DEBUG
defaultLogger.debug("\(URL(fileURLWithPath: file, isDirectory: false).deletingPathExtension().lastPathComponent): \(function) \(message)")
#endif
}
@discardableResult
public func debugResult<T>(_ result: T, file: String = #file, function: String = #function) -> T {
debugLog("returned: \(result)", file: file, function: function)
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment