Skip to content

Instantly share code, notes, and snippets.

@smosko
Created September 7, 2018 14:23
Show Gist options
  • Save smosko/5368ace349b85fa6215c7368d06593c4 to your computer and use it in GitHub Desktop.
Save smosko/5368ace349b85fa6215c7368d06593c4 to your computer and use it in GitHub Desktop.
Simple Swift Logger
import Foundation
public final class Logger {
public enum Level: String {
case verbose = "◻️"
case debug = "◼️"
case info = "🔹"
case warning = "🔸"
case error = "🔴"
}
public static let shared = Logger()
public func log(_ message: @autoclosure () -> Any,
level: Level = .verbose,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line) {
#if DEBUG
print("\(timestamp()) \(threadName()) \(level.rawValue) \(message()) [\(source(file, function, line))]")
#endif
}
private lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss.SSS"
return formatter
}()
private func timestamp() -> String {
return dateFormatter.string(from: Date())
}
private func threadName() -> String {
if Thread.isMainThread {
return "main"
} else if let name = Thread.current.name, !name.isEmpty {
return name
} else {
return String(format: "%p", Thread.current)
}
}
private func source(_ file: StaticString, _ function: StaticString, _ line: UInt) -> String {
let url = URL(fileURLWithPath: String(describing: file))
let filename = url.deletingPathExtension().lastPathComponent
return "\(filename).\(function):\(line)"
}
}
// MARK: Convenience free functions
public func log(_ message: @autoclosure () -> Any,
level: Logger.Level = .verbose,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line) {
Logger.shared.log(message, level: .verbose, file: file, function: function, line: line)
}
public func debug(_ message: @autoclosure () -> Any,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line) {
Logger.shared.log(message, level: .debug, file: file, function: function, line: line)
}
public func info(_ message: @autoclosure () -> Any,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line) {
Logger.shared.log(message, level: .info, file: file, function: function, line: line)
}
public func warn(_ message: @autoclosure () -> Any,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line) {
Logger.shared.log(message, level: .warning, file: file, function: function, line: line)
}
public func error(_ message: @autoclosure () -> Any,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line) {
Logger.shared.log(message, level: .error, file: file, function: function, line: line)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment