iosswiftcocoalumberjack

Manually create new log file with CocoaLumberjack


I have configure CocoaLumberjack like this:

// CocoaLumberjack
DDLog.add(DDASLLogger.sharedInstance, with: DDLogLevel.debug)
DDLog.add(DDTTYLogger.sharedInstance, with: DDLogLevel.debug)
DDTTYLogger.sharedInstance.colorsEnabled = true
fileLogger = DDFileLogger.init()
fileLogger?.doNotReuseLogFiles = true // Always create a new log file when apps starts
fileLogger?.rollingFrequency = 86400 // 24 Hours
fileLogger?.maximumFileSize = 0 // Force log to only roll after 24 hours
fileLogger?.logFileManager.maximumNumberOfLogFiles = 1 // Keeps 1 log file plus active log file
DDLog.add(fileLogger!, with: DDLogLevel.debug)

In my app, I'll want to have the following log system:

The entry point to my app is a Login View Controller. I want to write log entries here so I can see if everything goes okey. If the user login correctly, I want to roll/archive that log and create a new one for that user. In this new log, I'll keep errors that occurs during user session. If users logout, I want to again roll/archive the log and create a new one. Before rolling/archiving the log I always send it to my server, so I can delete it from the device.

I'm trying the following to roll/archive the log but I'm not succecing:

Server().sendUserLog(filePath: DDFileLogger().currentLogFileInfo.filePath, onSuccess: { // This function send the log to the server, if all goes good, I want to roll it. 
          print(">>>>>>>>>>>>>>>>>>>>> \(DDFileLogger().currentLogFileInfo.filePath)")
          DDFileLogger().rollLogFile(withCompletion: { 
            print("Log rolled")
            print(">>>>>>>>>>>>>>>>>>>>> \(DDFileLogger().currentLogFileInfo.filePath)")
          })
        }, onError: { (error) in
          DDLogError("LoginVC - sendUserLog Error: \(error)")
        })

Both print, before roll function and after roll function, print the same path and file name. So I'm not creating a new log file.

How can I create it?


Solution

  • The problem is you are creating a new DDFileLogger by using DDFileLogger(). You should store your fileLogger somewhere and call rollLogFile on the same instance. Something like this:

    let fileLogger = DDFileLogger()
    Server().sendUserLog(
        filePath: fileLogger.currentLogFileInfo.filePath, 
        onSuccess: { // This function send the log to the server, if all goes good, I want to roll it. 
            print(">>>>>>>>>>>>>>>>>>>>> \(fileLogger.currentLogFileInfo.filePath)")
            fileLogger.rollLogFile(withCompletion: { 
                print("Log rolled")
                print(">>>>>>>>>>>>>>>>>>>>> \(fileLogger.currentLogFileInfo.filePath)")
            })
        }, 
        onError: { (error) in
          DDLogError("LoginVC - sendUserLog Error: \(error)")
        })