先看效果图
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
}
}
网友评论