Swift 自定义日志类 Log

前言:

iOS并没有像Android那样提供Log类进行日子管理,自带的print与NSLog也显得很朴素。第三方框架想XG等也很优秀,但是也需要添加依赖和学习成本。这里我们利用Swift的关键字保留(类似于c语言的预编译命令),可以很简单实现超轻量但却功能强大的日志管理工具,考虑到大多数项目不像服务端进行持久化管理,这里仅输出控制台即可。

这里我们提供五个级别,即琐碎(Verbose)、调试(Debug)、信息(Info)、警告(Warning)、错误(Error),再辅以时间、文件名、行数、方法名及颜色符号来进行区分。考虑到琐碎级别的日志很多,就不予以时间显示。

//
//  Log.swift
//  Log
//
//  Created by Eldest's MacBook on 2021/11/25.
//

import Foundation

class Log{
    
    public static func verbose<T>(_ message: T, file: String = #file, function: String = #function, line: Int = #line) {
        #if DEBUG
            let fileName = (file as NSString).lastPathComponent
            print("------>  [VERBOSE] \(fileName):\(line) \(function) || \(message) ")
        #endif
    }
    
    public static func debug<T>(_ message: T, file: String = #file, function: String = #function, line: Int = #line) {
        #if DEBUG
            let fileName = (file as NSString).lastPathComponent
            let dformatter = DateFormatter()
            dformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let dateStr = dformatter.string(from: Date())
            print("------>  [DEBUG] \(dateStr) \(fileName):\(line) \(function) || \(message) ")
        #endif
    }
    
    public static func info<T>(_ message: T, file: String = #file, function: String = #function, line: Int = #line) {
        #if DEBUG
            let fileName = (file as NSString).lastPathComponent
            let dformatter = DateFormatter()
            dformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let dateStr = dformatter.string(from: Date())
            print("------>  [INFO] \(dateStr) \(fileName):\(line) \(function) || \(message) ")
        #endif
    }
    
    public static func warning<T>(_ message: T, file: String = #file, function: String = #function, line: Int = #line) {
        #if DEBUG
            let fileName = (file as NSString).lastPathComponent
            let dformatter = DateFormatter()
            dformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let dateStr = dformatter.string(from: Date())
            print("------>  [WARNING] \(dateStr) \(fileName):\(line) \(function) || \(message) ")
        #endif
    }
    
    public static func error<T>(_ message: T, file: String = #file, function: String = #function, line: Int = #line) {
        #if DEBUG
            let fileName = (file as NSString).lastPathComponent
            let dformatter = DateFormatter()
            dformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let dateStr = dformatter.string(from: Date())
            print("------>  [ERROR] \(dateStr) \(fileName):\(line) \(function) || \(message) ")
        #endif
    }
    
}

使用的时候使用Log.info(“test”) 这样编写的静态方法即可,如果有读者是Java开发的,可以把静态方法再简写来适应。

你可能感兴趣的:(iOS,xcode,swift,ios)