日志上报
- 采集日志到本地文件。
- 文件大小限制为1M,超过限制拷贝到备份文件。
- 定义上报时机,上报日志文件
import Foundation
class HXLogger {
static let shared = HXLogger()
private let logFileName = "app_log.txt"
private var logFileURL: URL?
private let maxLogFileSize: Int = 1024 * 1024 // 1MB
private init() {
configureLogFile()
}
private func configureLogFile() {
// 获取应用沙盒中的Documents目录
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
return
}
// 创建日志文件URL
logFileURL = documentsDirectory.appendingPathComponent(logFileName)
// 如果日志文件已存在,删除旧文件
if FileManager.default.fileExists(atPath: logFileURL?.path ?? "") {
do {
try FileManager.default.removeItem(at: logFileURL!)
} catch {
print("Failed to remove existing log file: \(error)")
}
}
}
func log(message: String) {
guard let logFileURL = logFileURL else {
return
}
do {
// 获取文件大小
let fileSize = try FileManager.default.attributesOfItem(atPath: logFileURL.path)[.size] as? Int ?? 0
// 如果文件大小超过限制,备份旧文件并创建新文件
if fileSize >= maxLogFileSize {
try backupLogFile()
}
// 将日志信息追加到文件末尾
try message.appendLineToURL(fileURL: logFileURL)
} catch {
print("Failed to write log message to file: \(error)")
}
}
func backupLogFile() throws {
guard let logFileURL = logFileURL else {
return
}
// 在文件名中添加时间戳作为备份文件的名称
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddHHmmss"
let timestamp = dateFormatter.string(from: Date())
let backupFileName = logFileName.appendingFormat("_%@", timestamp)
// 生成备份文件URL
let backupFileURL = logFileURL.deletingLastPathComponent().appendingPathComponent(backupFileName)
// 将当前日志文件移动到备份文件位置
try FileManager.default.moveItem(at: logFileURL, to: backupFileURL)
// 创建新的日志文件
configureLogFile()
}
}
// 扩展String类型,用于将字符串追加到文件末尾
extension String {
func appendLineToURL(fileURL: URL) throws {
try (self + "\n").appendToURL(fileURL: fileURL)
}
func appendToURL(fileURL: URL) throws {
let data = self.data(using: String.Encoding.utf8)!
try data.append(fileURL: fileURL)
}
}
// 扩展Data类型,用于将数据追加到文件末尾
extension Data {
func append(fileURL: URL) throws {
if let fileHandle = try? FileHandle(forWritingTo: fileURL) {
defer {
fileHandle.closeFile()
}
fileHandle.seekToEndOfFile()
fileHandle.write(self)
} else {
try write(to: fileURL, options: .atomic)
}
}
}
网友评论