Skip to content

Instantly share code, notes, and snippets.

@aryamansharda
Created July 4, 2021 03:05
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save aryamansharda/d153667b25e03eef9b0ac71de43e801b to your computer and use it in GitHub Desktop.
Save aryamansharda/d153667b25e03eef9b0ac71de43e801b to your computer and use it in GitHub Desktop.
Logging In Swift [The Right Way]
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