我想使用XCGLogger 3.0在用Swift 2编写的iOS9应用程序中进行日志记录。在AppDelegate中,我定义了
let log = XCGLogger.defaultInstance()
并在应用程序中:didFinishLaunchingWithOptions我使用以下命令进行设置:
log.setup(.Debug, showThreadName: true, showLogLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: "/tmp/app.log", fileLogLevel: .Debug)
当我在模拟器中启动应用程序时,我在XCode 7的控制台中看到XCGLogger的输出。输出为:
2015-11-04 18:28:40.798 [Info]> myapp版本:1.0 Build:1 PID:49243
2015-11-04 18:28:40.798 [Info]> XCGLogger版本:3.0 - LogLevel:Debug
2015-11-04 18:28:40.801 [Info]> XCGLogger写入日志:file:///tmp/app.log
但是当我查看正确模拟器实例的沙箱文件系统(使用SimPholders2)时,没有日志文件app.log。
当我在我的iPhone 6上启动应用程序时情况更糟.XCode控制台中的输出是:
2015-11-04 18:36:14.692 [错误]>尝试打开日志文件进行写入失败:无法完成操作。 (可可错误2。)
我也尝试了不同的方式,例如" /tmp/app.log"," Library / Caches / de.myidentifier.myapp / app.log"," / Library /Caches/de.myidentifier.myapp/app.log"等但没有成功......
我做错了什么?
答案 0 :(得分:11)
在iOS上,您无法写入/tmp
文件夹。您需要确保路径位于应用程序的沙箱中。
为此,您需要向系统询问缓存目录。 XCGLogger中的示例应用程序包含了执行此操作的代码,但我也将其包含在此处。
试试这个:
let cacheDirectory: NSURL = {
let urls = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)
return urls[urls.endIndex - 1]
}()
let logPath: NSURL = cacheDirectory.URLByAppendingPathComponent("app.log")
log.setup(.Debug, showThreadName: true, showLogLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: logPath, fileLogLevel: .Debug)
答案 1 :(得分:2)
如果有人需要这里是Swave 4版本的Dave Wood的例子。 感谢XCGLogger,它是一个很棒的工具。
let cacheDirectory: URL = {
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
return urls[urls.endIndex - 1]
}()
let logPath = cacheDirectory.appendingPathComponent("app.log")
let fileDestination = FileDestination(writeToFile: logPath, identifier: "testLogger.fileDestination", shouldAppend: true)