I want to use XCGLogger 3.0 to do the logging in an iOS9 app written in Swift 2. In the AppDelegate, I define
let log = XCGLogger.defaultInstance()
and in application:didFinishLaunchingWithOptions I do the setup with:
log.setup(.Debug, showThreadName: true, showLogLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: "/tmp/app.log", fileLogLevel: .Debug)
When I start the app in the simulator I see the output of XCGLogger in the console of XCode 7. The output is:
2015-11-04 18:28:40.798 [Info] > myapp Version: 1.0 Build: 1 PID: 49243
2015-11-04 18:28:40.798 [Info] > XCGLogger Version: 3.0 - LogLevel: Debug
2015-11-04 18:28:40.801 [Info] > XCGLogger writing to log to: file:///tmp/app.log
But when I look at the sandbox filesystem of the correct simulator instance (using SimPholders2), there is no logfile app.log.
It's even worse when I start the app on my IPhone 6. The output in the XCode console is:
2015-11-04 18:36:14.692 [Error] > Attempt to open log file for writing failed: The operation couldn’t be completed. (Cocoa error 2.)
I also tried different pathes like "/tmp/app.log", "Library/Caches/de.myidentifier.myapp/app.log", "/Library/Caches/de.myidentifier.myapp/app.log" etc. but without success...
What am I doing wrong?
On iOS, you can't just write to the /tmp
folder. You need to ensure the path is in the application's sandbox.
To do that, you need to ask the system for your cache directory. The sample app in XCGLogger includes the code to do that, but I'll include it here as well.
Try this:
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)