Skip to content

Instantly share code, notes, and snippets.

@fxm90
Last active February 9, 2026 20:37
Show Gist options
  • Select an option

  • Save fxm90/08a187c5d6b365ce2305c194905e61c2 to your computer and use it in GitHub Desktop.

Select an option

Save fxm90/08a187c5d6b365ce2305c194905e61c2 to your computer and use it in GitHub Desktop.
A simple log extension on `String` using literal expressions
//
// 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 debug
case info
case warning
case error
var emoji: Character {
switch self {
case .debug: "πŸ”"
case .info: "ℹ️"
case .warning: "⚠️"
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 timestamp = Self.logDateFormatter.string(from: Date())
let filename = URL(fileURLWithPath: file).lastPathComponent
print("\(level.emoji) \(timestamp) [\(filename):\(line)] \(function) - \(self)")
#endif
}
}
@fxm90
Copy link
Copy Markdown
Author

fxm90 commented Feb 9, 2026

Example Output

"Lorem Ipsum Dolor Sit Amet πŸ‘‹".log(level: .debug)
"Lorem Ipsum Dolor Sit Amet πŸ‘‹".log(level: .info)
"Lorem Ipsum Dolor Sit Amet πŸ‘‹".log(level: .warning)
"Lorem Ipsum Dolor Sit Amet πŸ‘‹".log(level: .error)

πŸ” 2026-02-09 21:35:00.000 [String+Log.swift:58] viewDidLoad() - Lorem Ipsum Dolor Sit Amet πŸ‘‹
ℹ️ 2026-02-09 21:35:00.000 [String+Log.swift:59] viewDidLoad() - Lorem Ipsum Dolor Sit Amet πŸ‘‹
⚠️ 2026-02-09 21:35:00.000 [String+Log.swift:60] viewDidLoad() - Lorem Ipsum Dolor Sit Amet πŸ‘‹
🚨 2026-02-09 21:35:00.000 [String+Log.swift:61] viewDidLoad() - Lorem Ipsum Dolor Sit Amet πŸ‘‹

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