Skip to content

Instantly share code, notes, and snippets.

@kraigspear
Last active March 17, 2021 05:23
Show Gist options
  • Save kraigspear/6bf82f8e73ad6f316b774979c1eaa300 to your computer and use it in GitHub Desktop.
Save kraigspear/6bf82f8e73ad6f316b774979c1eaa300 to your computer and use it in GitHub Desktop.
Logger in swift
//
// Logger.swift
// Klimate
//
// Created by Kraig Spear on 10/23/20.
//
import Foundation
public protocol Logger {
func log(level: LogLevel,
message: String,
context: String?,
file: StaticString,
function: StaticString,
line: UInt)
}
public extension Logger {
func debug(_ message: String,
context: String? = nil,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line) {
log(level: .debug,
message: message,
context: context,
file: file,
function: function,
line: line)
}
func info(_ message: String,
context: String? = nil,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line) {
log(level: .info,
message: message,
context: context,
file: file,
function: function,
line: line)
}
func warning(_ message: String,
context: String? = nil,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line) {
log(level: .warn,
message: message,
context: context,
file: file,
function: function,
line: line)
}
func error(_ message: String,
context: String? = nil,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line) {
log(level: .error,
message: message,
context: context,
file: file,
function: function,
line: line)
}
func verbose(_ message: String,
context: String? = nil,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line) {
log(level: .verbose,
message: message,
context: context,
file: file,
function: function,
line: line)
}
func toMessage(file: StaticString,
function: StaticString,
line: UInt,
message: String) -> String {
let fileName = URL(fileURLWithPath: String(describing: file)).lastPathComponent.split(separator: ".").map(String.init).first ?? ""
let functionStr = String(describing: function).split(separator: "(").first!
return "\(fileName).\(functionStr):\(line) - \(message)"
}
}
public enum LogLevel {
case info
case debug
case warn
case error
case verbose
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment