Skip to content

Instantly share code, notes, and snippets.

@KrisRJack
Last active May 30, 2021 20:36
Show Gist options
  • Save KrisRJack/9c316aa3aa240a6be3127bba14cd0b4d to your computer and use it in GitHub Desktop.
Save KrisRJack/9c316aa3aa240a6be3127bba14cd0b4d to your computer and use it in GitHub Desktop.
Better logging in Swift
//
// Logging.swift
// Created by Kristopher Jackson
//
import Foundation
class Log {
enum LogType: String {
case verbose = "🟣 VERBOSE"
case debug = "🟢 DEBUG"
case info = "🔵 INFO"
case warning = "🟡 WARNING"
case error = "🔴 ERROR"
}
@discardableResult
required init(_ text: Any, type: LogType, file: String = #file, function: String = #function, line: Int = #line) {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = .current
dateFormatter.dateStyle = DateFormatter.Style.short
dateFormatter.timeStyle = DateFormatter.Style.medium
print("\(dateFormatter.string(from: Date())) => \(type.rawValue) => \(self.stripParams(function: function)) => \(line) - \(text)")
}
/// removes the parameters from a function
private func stripParams(function: String) -> String {
var f = function
if let indexOfBrace = f.find("(") {
#if swift(>=4.0)
f = String(f[..<indexOfBrace])
#else
f = f.substring(to: indexOfBrace)
#endif
}
f += "()"
return f
}
}
extension String {
/// cross-Swift-compatible index
func find(_ char: Character) -> Index? {
#if swift(>=5)
return self.firstIndex(of: char)
#else
return self.index(of: char)
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment