美文网首页
swift 打印日志生成TXT文件,调试用

swift 打印日志生成TXT文件,调试用

作者: UILable攻城狮 | 来源:发表于2023-07-27 11:15 被阅读0次

先看效果图

image.png

废话不多说 直接上代码

  • 定义一个无类方法 全局调用
 public func CACSLogPrint(_ item: Any? = nil, title: String = "", timeVisible: Bool = true, file: String = #file, function: String = #function) {
    let titleTemp = title.trimmingCharacters(in: .whitespacesAndNewlines)
    let titleString = titleTemp.count > 0 ? "[\(titleTemp)]: " : ""
    let filename = ((file as NSString).lastPathComponent as NSString).deletingPathExtension
    let timeString = timeVisible ? "\(Date().string(withFormat: "yyyy-MM-dd HH:mm:ss.SSS")) " : ""
    let itemString = (item == nil) ? "" : ": \(item!)"
    let output = "\(timeString)\(titleString)[\(filename) \(function)]\(itemString)"
    CALogPrintManager.shared.log(output)
    print(output)
}
  • 实现保存日志类
public class CALogPrintManager {
    
    static let shared = CALogPrintManager()
    
    private lazy var logFolderPath: String = {
        NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/Log/CommnuicationShareSocket"
    }()
    
    private lazy var logPath: String = {
        logFolderPath + "/" + Date().string(withFormat: "yyyyMMdd_HHmmss") + ".txt"
    }()
    
    func log(_ output: String) {
       
        
//        #if DEBUG
        
        if !FileManager.default.fileExists(atPath: logPath) {
            if !FileManager.default.fileExists(atPath: logFolderPath) {
                try? FileManager.default.createDirectory(atPath: logFolderPath, withIntermediateDirectories: true)
            }
            FileManager.default.createFile(atPath: logPath, contents: nil)
        }
        if let handle = FileHandle(forWritingAtPath: logPath) {
            handle.seekToEndOfFile()
            if let data = (output + "\n").data(using: .utf8) {
                handle.write(data)
            }
            handle.closeFile()
        }
        
//        #endif
    }
    
    

}

相关文章

网友评论

      本文标题:swift 打印日志生成TXT文件,调试用

      本文链接:https://www.haomeiwen.com/subject/nvlhpdtx.html