Skip to content

Instantly share code, notes, and snippets.

@aijaz
Forked from chockenberry/Debug.swift
Created May 23, 2021 17:56
Show Gist options
  • Save aijaz/aa7673c509ec76fb7edbeb597be3bdaa to your computer and use it in GitHub Desktop.
Save aijaz/aa7673c509ec76fb7edbeb597be3bdaa 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.
// Usage:
//
// SplineReticulationManager.swift:
//
// func reticulationFunction() -> Float {
// debugLog() // prints "2019-10-04 11:52:28 SplineReticulationManager: reticulationFunction() called"
//
// let splineCount = Int.random(in: 0...1000)
// debugLog("reticulating \(splineCount) splines") // prints "2019-10-04 11:52:28 SplineReticulationManager: reticulationFunction() reticulating 123 splines"
//
// return debugResult(Float.random(in: 0...1)) // prints "2019-10-04 11:52:28 SplineReticulationManager: reticulationFunction() returned: 0.12345"
// }
import Foundation
func releaseLog(_ message: String = "called", file: String = #file, function: String = #function) {
let timestamp = ISO8601DateFormatter.string(from: Date(), timeZone: TimeZone.current, formatOptions: [.withYear, .withMonth, .withDay, .withDashSeparatorInDate, .withTime, .withColonSeparatorInTime, .withSpaceBetweenDateAndTime])
print("\(timestamp) \(URL(fileURLWithPath: file, isDirectory: false).deletingPathExtension().lastPathComponent): \(function) \(message)")
}
func debugLog(_ message: String = "called", file: String = #file, function: String = #function) {
#if DEBUG
let timestamp = ISO8601DateFormatter.string(from: Date(), timeZone: TimeZone.current, formatOptions: [.withYear, .withMonth, .withDay, .withDashSeparatorInDate, .withTime, .withColonSeparatorInTime, .withSpaceBetweenDateAndTime])
print("\(timestamp) \(URL(fileURLWithPath: file, isDirectory: false).deletingPathExtension().lastPathComponent): \(function) \(message)")
#endif
}
@discardableResult
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