Search code examples
iosswiftcocoalumberjack

CocoaLumberjack Swift - Check if log level includes .verbose


I've been using CocoaLumberjack in Swift and Obj-C for years with pod 'CocoaLumberjack/Swift'.

I'm converting code from Obj-C to Swift and can't figure out how to translate this into Swift:

- (void)functionThatGetsCalledAlot {
  if (ddLogLevel & DDLogLevelVerbose) {
      DDLogVerbose(@"Log message");
      ...Many more log statements...
  }
}

I only use this in rare performance sensitive cases where I only want to execute some block of code based on the log level. The condition will be true if the dynamic log level, ddLogLevel, includes DDLogLevelVerbose which is true for DDLogLevelVerbose and DDLogLevelAll.

How do I write this in Swift?


Solution

  • The swifty thing to use here would be an OptionSet type. Log levels are perfectly suited for this, but unfortunately in this case it is bridged from ObjC as an enum.

    Since the underlying DDLogFlag conforms to OptionSet, we can build a workaround:

    extension DDLogLevel {
        var flag: DDLogFlag {
            return DDLogFlag(rawValue: rawValue)
        }
    }
    

    which can then be used like this:

    let logLevel = DDLogLevel.all
    
    if logLevel.flag.contains(.verbose) {
        print("Verbose is on")
    }