Search code examples
iosswiftcocoalumberjack

CocoaLumberjack in Swift, how to print line number and filne name


I'm new to CocoaLumberjack and I get it to work on Swift following this. If I try to print logs doing:

DDLogDebug("Debug")
DDLogInfo("Info")
DDLogWarn("Warning")
DDLogVerbose("Verbose")
DDLogError("Error")

Everything works fine and I get all the levels printed as my defaultDebugLevel is DDLogLevel.Verbose.

But I can't find/find out how to print the line or the filename with the log. Any idea?

Thanks a lot!!


Solution

  • After some more research I found that you have to create a log formatter, this log formatter is a subclass of DDDispatchQueueLogFormatter and you have to override a function that receives a DDLogMessage and returns a String, for example:

    import Foundation
    import CocoaLumberjack.DDDispatchQueueLogFormatter
    
    class LogFormatter: DDDispatchQueueLogFormatter {
      let dateFormatter: NSDateFormatter
    
      override init() {
        dateFormatter = NSDateFormatter()
        dateFormatter.formatterBehavior = .Behavior10_4
        dateFormatter.dateFormat = "HH:mm"
    
        super.init()
      }
    
      override func formatLogMessage(logMessage: DDLogMessage!) -> String {
        let dateAndTime = dateFormatter.stringFromDate(logMessage.timestamp)
        return "\(dateAndTime) [\(logMessage.fileName):\(logMessage.line)]: \(logMessage.message)"
      }
    }
    

    Then you just have to add your formatter like this in your AppDelegate or wherever you are setting CocaLumberJack:

    DDTTYLogger.sharedInstance().logFormatter = LogFormatter()
    

    Hope it helps someone!