Last active
December 12, 2024 12:00
-
-
Save fxm90/08a187c5d6b365ce2305c194905e61c2 to your computer and use it in GitHub Desktop.
A simple log extension on `String` using literal expressions
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
// | |
// String+Log.swift | |
// | |
// Created by Felix Mau on 16/09/18. | |
// Copyright © 2018 Felix Mau. All rights reserved. | |
// | |
import Foundation | |
extension String { | |
// MARK: - Types | |
enum LogLevel { | |
case info | |
case error | |
} | |
// MARK: - Private properties | |
/// The formatter we use to prefix the log output with the current date and time. | |
private static let logDateFormatter: DateFormatter = { | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss.SSS" | |
return dateFormatter | |
}() | |
// MARK: - Public methods | |
func log(level: LogLevel, file: String = #file, function _: String = #function, line: UInt = #line) { | |
#if DEBUG | |
let logEmoji: Character | |
switch level { | |
case .info: | |
logEmoji = "ℹ️" | |
case .error: | |
logEmoji = "⚠️" | |
} | |
let formattedDate = Self.logDateFormatter.string(from: Date()) | |
let filename = URL(fileURLWithPath: file).lastPathComponent | |
print("\(logEmoji) \(formattedDate) – \(filename):\(line) – \(self)") | |
#endif | |
} | |
} | |
// Usage example | |
"Lorem Ipsum Dolor Sit Amet 👋".log(level: .info) | |
"Lorem Ipsum Dolor Sit Amet 👋".log(level: .error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment