目的︰用檔案記錄log,以時間組成檔名(yyyyMMddHHmmss),只保留7天
做法︰
1. 使用XCGLogger來記錄log
2. 每次APP啟動時,檢查log檔案是否有超過7天的,超過就刪除
// AppDelegate.swift
import XCGLogger
struct MyVariables {
static let logger = XCGLogger.defaultInstance()
static let documentsPath = NSHomeDirectory() + "/Documents"
}
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// 清除7天前的log檔
cleanOldLogFile()
// 產生此次log的檔名
let postFixFormatter = NSDateFormatter()
postFixFormatter.dateFormat = "yyyyMMddHHmmss"
postFixFormatter.locale = NSLocale.currentLocale()
let logFileName = "Ticket_" + postFixFormatter.stringFromDate(NSDate()) + ".log"
let logFileWithFullPath = MyVariables.documentsPath.stringByAppendingString("/\(logFileName)")
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
dateFormatter.locale = NSLocale.currentLocale()
// print to log file
MyVariables.logger.setup(.Debug, showThreadName: true, showLogLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: logFileWithFullPath, fileLogLevel: .Debug)
// ...
return true
}
func cleanOldLogFile(){
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
do {
// 找出所有的*.log檔
let directoryUrls = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
let logFiles = directoryUrls.filter(){ $0.pathExtension == "log" }.map{ $0.lastPathComponent }
// 7天前的Date
let sevenDaysAge = NSDate().dateByAddingTimeInterval(-7*24*60*60)
let logFileDateFormatter = NSDateFormatter()
logFileDateFormatter.dateFormat = "yyyyMMddHHmmss"
for logFileName in logFiles {
let nameSplitedArray = logFileName!.componentsSeparatedByString("_")
// swift中字符串截取方法(substring)http://www.swiftmi.com/topic/76.html
let index = nameSplitedArray[1].endIndex.advancedBy(-4) // 從字串最後面往回4個位置
let logFileDate = logFileDateFormatter.dateFromString(nameSplitedArray[1].substringToIndex(index))
if logFileDate!.isLessThanDate(sevenDaysAge) { // 比7天前的日期還小(早) -> 要刪除
let fp = MyVariables.documentsPath.stringByAppendingString("/\(logFileName!)")
print("Delete old log file: \(logFileName!)")
// 刪除檔案
try NSFileManager.defaultManager().removeItemAtPath(fp)
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
留言
張貼留言