Skip to content

Instantly share code, notes, and snippets.

@fxm90 fxm90/String+Log.swift
Last active Feb 11, 2019

Embed
What would you like to do?
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 release
case debug
}
// MARK: - Private properties
/// Returns the current date/time as string.
private var logDate: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss.SSS"
let now = Date()
return dateFormatter.string(from: now)
}
// MARK: - Public methods
func log(level: LogLevel, file: String = #file, function: String = #function, line: UInt = #line) {
let logPrefix = self.logPrefix(fileName: filename(filePath: file),
functionName: function,
line: line)
let logString = "\(logDate) - \(logPrefix) - \(self)"
switch level {
case .release:
print(logString)
case .debug:
#if DEBUG
print(logString)
#endif
}
}
// MARK: - Private methods
/// Extracts the filename of the entire path.
private func filename(filePath: String) -> String {
return URL(fileURLWithPath: filePath).lastPathComponent
}
/// Returns the prefix (containing file name, function name and line) for the log statement.
private func logPrefix(fileName: String, functionName: String, line: UInt) -> String {
let combinedNames = "\(fileName) - \(functionName):\(line)"
return combinedNames
}
}
// Usage example
"Lorem Ipsum Dolor Sit Amet 👋".log(level: .release)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.