Skip to content

Instantly share code, notes, and snippets.

@fxm90
Last active February 4, 2023 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fxm90/08a187c5d6b365ce2305c194905e61c2 to your computer and use it in GitHub Desktop.
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 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