我注意到我的NSLog (我也尝试过用os_log)语句在控制台应用程序中不能一致地显示。
下面是我的应用程序启动时运行的一些代码。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
NSLog("xyz didFinishLaunchingWithOptions")
FirebaseApp.configure()
NSLog("xyz FirebaseApp.configure() done")
let db = FirestoreDelegate.db()
let now = Date()
NSLog("xyz about to write")
db.collection("atest").document(DateUtils.formatTimestampGMT(now)).setData(["ts": now, "note":"delegate startup"]) {
err in
if let err = err {
NSLog ("xyz error ats \(err)")
return
}
NSLog("xyz wrote to ats \(DateUtils.formatTimestampGMT(now))")
}
NSLog("xyz after write")
... extraneous code removed
}当我运行时,有时会看到"xyz didFinishLaunchingWithOptions“和"wrote to ats",但没有看到其他日志语句。有时我会看到它们全部,但这是相当不一致的。它们是被过滤掉了还是被优化了?
我没有通过xcode进行调试,我只是在我的手机上运行应用程序,并通过我电脑上的控制台应用程序查看日志。
发布于 2019-05-31 03:14:50
我不明白为什么日志记录不一致。相反,我创建了一个写入文件的自定义记录器。
public class FileWriter {
static func getTs() -> String {
let timestampFormat = DateFormatter()
timestampFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
return timestampFormat.string(from: Date())
}
static func write(_ text: String) {
do {
let dir: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! as URL
let url = dir.appendingPathComponent("log.txt")
if !FileManager.default.fileExists(atPath: url.path) {
FileManager.default.createFile(atPath: url.path, contents: nil, attributes: nil)
}
let fileHandle = try FileHandle(forWritingTo: url)
let line = "\(getTs()) \(text)\n"
let data = line.data(using: String.Encoding.utf8)!
fileHandle.seekToEndOfFile()
fileHandle.write(data)
fileHandle.closeFile()
} catch let error as NSError {
print ("error \(error)")
}
}
}为了读取文件,我在我的Info.plist "UIFileSharingEnabled“,"LSSupportsOpeningDocumentsInPlace”中添加了以下密钥,然后我就可以用文件应用程序在手机上打开文件了。
https://stackoverflow.com/questions/56369801
复制相似问题