Reputation: 34948
I've noticed that my NSLog (and I've also tried it with os_log) statements are not showing up consistently in the console application.
Here's some code that runs when my app starts up.
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
}
When I run, sometimes I see "xyz didFinishLaunchingWithOptions" and "wrote to ats", but none of the other log statements. Sometimes I see them all, but it's pretty inconsistent. Are they getting filtered or optimized out somehow?
I'm not debugging through xcode, I'm just running the app on my phone and viewing the logs through the console app on my computer.
Upvotes: 0
Views: 341
Reputation: 34948
I didn't figure out why the logging is inconsistent. Instead I created a custom logger that writes to a file.
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)")
}
}
}
To read the file, I added the following keys to my Info.plist "UIFileSharingEnabled" , "LSSupportsOpeningDocumentsInPlace" and then I could open the file on my phone with the Files app.
Upvotes: 1