Created
January 14, 2023 22:05
-
-
Save levochkaa/0c063059d4c31bc8033239250e2f2468 to your computer and use it in GitHub Desktop.
Best Logger in Swift ever (and the easiest to use)
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
// Logger.swift | |
import Foundation | |
import os.log | |
// swiftlint:disable line_length | |
func log(_ messages: Any..., file: String = #fileID, function: String = #function, line: Int = #line) { | |
// actually impossible cases | |
guard let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String else { | |
return print("Unable to get App Name") | |
} | |
guard let projectName = Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String else { | |
return print("Unable to get Project Name") | |
} | |
guard let fileName = file.split(separator: "/").last?.split(separator: ".").first else { | |
return print("Unable to get fileName info for \(file), with \(messages)") | |
} | |
let logger = os.Logger(subsystem: appName, category: projectName) | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = "HH:mm:ss" | |
let date = dateFormatter.string(from: Date.now) | |
var output = messages.map { "\($0)" }.joined(separator: ";\n") | |
#if DEBUG | |
// privacy: .public - to see logs in Console.app, when running on a real device | |
logger.log("[\(date, privacy: .public)] [\(fileName, privacy: .public)] [\(function, privacy: .public)] [\(line, privacy: .public)]\n\(output, privacy: .public)") | |
#else | |
logger.log("[\(date)] [\(fileName)] [\(function)] [\(line)]\n\(output)") | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I suppose, it is better, to move
appName
,projectName
,logger
anddateFormatter
to global scope to just use them inlog(_:)