Skip to content

Instantly share code, notes, and snippets.

@vinhnx
Forked from atierian/NetworkLogger.swift
Created May 21, 2022 14:09
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 vinhnx/d314d41bf4d1bc283a5c914ec17ad6d0 to your computer and use it in GitHub Desktop.
Save vinhnx/d314d41bf4d1bc283a5c914ec17ad6d0 to your computer and use it in GitHub Desktop.
Network Logger
import Foundation
public protocol NetworkLoggable {
func log<T: CustomStringConvertible>(
label: String,
value: T?,
level: NetworkLogger,
function: StaticString,
line: UInt,
file: String
)
}
extension NetworkLoggable {
public func log<T: CustomStringConvertible>(
label: String,
value: T?,
level: NetworkLogger,
function: StaticString,
line: UInt,
file: String
) {
#if DEBUG
let fileName = ((file as NSString).lastPathComponent as NSString).deletingPathExtension
let thread = Thread.isMainThread ? "MAIN" : "BG"
let threadID = String(format: "%x", pthread_mach_thread_np(pthread_self()))
let value = value?.description ?? "nil"
print("[\(Date().logTimeStamp)] [\(fileName):\(line)] [\(function)] [\(thread):\(threadID)] [\(label): \(value)]")
#endif
}
}
fileprivate extension Date {
var logTimeStamp: String {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss.SSS"
return formatter.string(from: self)
}
}
struct StandardLogger: NetworkLoggable { }
public struct NetworkLogger {
public static var logger: NetworkLoggable = StandardLogger()
public var verbosity: Int
public func log<T: CustomStringConvertible>(
label: String,
value: @autoclosure () -> T?,
level: NetworkLogger,
function: StaticString = #function,
line: UInt = #line,
file: String = #file
) {
guard level.verbosity <= verbosity else { return }
NetworkLogger.logger.log(label: label, value: value(), level: level, function: function, line: line, file: file)
}
}
extension NetworkLogger {
static let debug = NetworkLogger(verbosity: 6)
static let info = NetworkLogger(verbosity: 5)
static let notice = NetworkLogger(verbosity: 4)
static let warning = NetworkLogger(verbosity: 3)
static let error = NetworkLogger(verbosity: 2)
static let critical = NetworkLogger(verbosity: 1)
static let none = NetworkLogger(verbosity: 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment