Created
February 20, 2022 13:27
-
-
Save st-small/8ce6a75fc7139464c68c3b93088acf87 to your computer and use it in GitHub Desktop.
Logging In Swift [The Right Way]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
enum Log { | |
enum LogLevel { | |
case info | |
case warning | |
case error | |
fileprivate var prefix: String { | |
switch self { | |
case .info: return "INFO" | |
case .warning: return "WARN ⚠️" | |
case .error: return "ALERT ❌" | |
} | |
} | |
} | |
struct Context { | |
let file: String | |
let function: String | |
let line: Int | |
var description: String { | |
return "\((file as NSString).lastPathComponent):\(line) \(function)" | |
} | |
} | |
static func info(_ str: StaticString, shouldLogContext: Bool = true, file: String = #file, function: String = #function, line: Int = #line) { | |
let context = Context(file: file, function: function, line: line) | |
Log.handleLog(level: .info, str: str.description, shouldLogContext: shouldLogContext, context: context) | |
} | |
static func warning(_ str: StaticString, shouldLogContext: Bool = true, file: String = #file, function: String = #function, line: Int = #line) { | |
let context = Context(file: file, function: function, line: line) | |
Log.handleLog(level: .warning, str: str.description, shouldLogContext: shouldLogContext, context: context) | |
} | |
static func error(_ str: StaticString, shouldLogContext: Bool = true, file: String = #file, function: String = #function, line: Int = #line) { | |
let context = Context(file: file, function: function, line: line) | |
Log.handleLog(level: .error, str: str.description, shouldLogContext: shouldLogContext, context: context) | |
} | |
fileprivate static func handleLog(level: LogLevel, str: String, shouldLogContext: Bool, context: Context) { | |
let logComponents = ["[\(level.prefix)]", str] | |
var fullString = logComponents.joined(separator: " ") | |
if shouldLogContext { | |
fullString += " ➜ \(context.description)" | |
} | |
#if DEBUG | |
print(fullString) | |
#endif | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment