Swift prints the file, function and line number where log is located

Put the following code in the const (constant) file

//获取打印的文件名、打印函数、打印行数
func printLog(_ msg: Any,file: NSString = #file,line: Int = #line,fn: String = #function) {
    
    
    #if DEBUG
    let t = String.formatDate(Date(), "yyyy-MM-dd HH:mm:ss.SSSSSS")
    let prefix = "\(t) \(file.lastPathComponent) -> \(fn) [第\(line)行] \(msg)";
    print(prefix)
    #endif
}

There is a String class method in the above method of getting the time, which I wrote in the class extension. The code is as follows:

extension String {
    
    
  static func formatDate(_ date:Date,_ format:String) -> String {
    
    
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: date)
     }
 }

use:

printLog("这是啥啊 ??? ")
//打印结果如下:
//2022-03-10 11:39:06.321000 TestFristController.swift -> viewDidLoad() [第94行] 这是啥啊 ???  

//打印变量
printLog("images == \(images)")
//2022-03-10 11:39:39.898000 TestThridController.swift -> jumbToOtherVC() [第77行] images == [<UIImage:0x2838dc120 anonymous {828, 1472}>, <UIImage:0x2838dc000 anonymous {828, 876}>]

With reference to this article, I have done it myself, thank the author for sharing

Guess you like

Origin blog.csdn.net/weixin_43259805/article/details/123397216