2015-11-04 58 views
3

我想用XCGLogger 3.0做日誌中寫的斯威夫特2.在AppDelegate中的iOS9應用程序,我定義XCGLogger 3.0沒有日誌文件寫入到文件系統(iOS版9)

let log = XCGLogger.defaultInstance() 

和應用中:didFinishLaunchingWithOptions我做的設置:

log.setup(.Debug, showThreadName: true, showLogLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: "/tmp/app.log", fileLogLevel: .Debug) 

當我開始在模擬器上我看到XCGLogger的輸出的XCode 7.輸出的控制檯應用程序是:

2015-11-04 18:28:40.798 [Info]> myapp版本:1.0 Build:1 PID:49243

2015-11-04 18:28:40.798 [Info]> XCGLogger Version:3.0 - LogLevel :調試

2015年11月4日18:28:40.801 [信息]> XCGLogger寫記錄到:文件:///tmp/app.log

但是當我在看沙盤的文件系統正確的模擬器實例(使用SimPholders2),沒有日誌文件app.log。

當我開始在我的IPhone應用它甚至更糟6.在Xcode控制檯輸出爲:

2015年11月4日18:36:14.692 [錯誤]>嘗試打開日誌文件寫入失敗:操作無法完成。 (可可錯誤2.)

我也嘗試不同pathes像 「/tmp/app.log」, 「庫/緩存/ de.myidentifier.myapp/app.log」,「/庫/緩存/解.myidentifier.myapp/app.log「等但沒有成功...

我在做什麼錯?

回答

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) 
+0

你做了我的一天,非常感謝!它現在有效! :-)來自Swift/iOS新手的問候,我仍然學到很多:-) – ikemuc

+1

沒問題,希望你找到XCGLogger有用! –

+1

是的,它幫助我找到了一個煩人的bug :-) – ikemuc

0

如果有人需要在這裏是斯威夫特4版戴夫伍德的榜樣。 謝謝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)