Skip to content

Instantly share code, notes, and snippets.

@aibobrov
Created September 14, 2018 08:39
Show Gist options
  • Save aibobrov/7493bdc928c336d69334d86b07009fd7 to your computer and use it in GitHub Desktop.
Save aibobrov/7493bdc928c336d69334d86b07009fd7 to your computer and use it in GitHub Desktop.
Simple logger for Swift
import Foundation
fileprivate extension String {
var sourceFileName: String {
let fileName = self.components(separatedBy: "/").last?.split(separator: ".").first ?? ""
return String(fileName)
}
}
public class Logger {
public var dateFormat: String = "hh:mm:ssSSS"
public var loggingSymbols: [String] = [
"🔬 VERBOSE",
"💬 DEBUG",
"ℹ️ INFO",
"⚠️ WARNING",
"‼️ ERROR"
]
public private(set) var isLoggingEnabled: Bool
public private(set) var maxLoggingPriority: Int
public init(isEnabled: Bool = true, maxLoggingPriority: Int = .max) {
isLoggingEnabled = isEnabled
self.maxLoggingPriority = maxLoggingPriority
}
}
private extension Logger {
private func log(_ objects: Any, priority: Int, filename: String, line: Int, funcName: String) {
#if DEBUG
if isLoggingEnabled && priority < maxLoggingPriority {
print("\(Date().string(with: dateFormat)) \(loggingSymbols[priority]) \(filename.sourceFileName).\(funcName):\(line) - \(objects)")
}
#endif
}
}
public extension Logger {
public func error(_ message: Any, filename: String = #file, line: Int = #line, column: Int = #column, funcName: String = #function) {
log(message, priority: 4, filename: filename, line: line, funcName: funcName)
}
public func warning(_ message: Any, filename: String = #file, line: Int = #line, column: Int = #column, funcName: String = #function) {
log(message, priority: 3, filename: filename, line: line, funcName: funcName)
}
public func info(_ message: Any, filename: String = #file, line: Int = #line, column: Int = #column, funcName: String = #function) {
log(message, priority: 2, filename: filename, line: line, funcName: funcName)
}
public func debug(_ message: Any, filename: String = #file, line: Int = #line, column: Int = #column, funcName: String = #function) {
log(message, priority: 1, filename: filename, line: line, funcName: funcName)
}
public func verbose(_ message: Any, filename: String = #file, line: Int = #line, column: Int = #column, funcName: String = #function) {
log(message, priority: 0, filename: filename, line: line, funcName: funcName)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment