Skip to content

Instantly share code, notes, and snippets.

@levochkaa
Created January 14, 2023 22:05
Show Gist options
  • Save levochkaa/0c063059d4c31bc8033239250e2f2468 to your computer and use it in GitHub Desktop.
Save levochkaa/0c063059d4c31bc8033239250e2f2468 to your computer and use it in GitHub Desktop.
Best Logger in Swift ever (and the easiest to use)
// 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
}
@levochkaa
Copy link
Author

levochkaa commented Jan 20, 2023

I suppose, it is better, to move appName, projectName, logger and dateFormatter to global scope to just use them in log(_:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment