Jesse
Jesse

Reputation: 1697

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?

Upvotes: 0

Views: 463

Answers (2)

Xavier Lowmiller
Xavier Lowmiller

Reputation: 1401

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")
}

Upvotes: 2

OOPer
OOPer

Reputation: 47886

I imported only little part of CocoaLumberjack, but this should work same as the Objective-C code above.

if (ddLogLevel.rawValue & DDLogLevel.verbose.rawValue) != 0 {
    ...    
}

(ADDITION)

But as far as I checked the original definition, this code (and your Objective-C code) returns true for all predefined log levels.

You may need to write something like this to hit only DDLogLevelVerbose and DDLogLevelAll.

(Objective-C)

if (ddLogLevel & DDLogFlagVerbose) {
    ...
}

(Swift)

if (ddLogLevel.rawValue & DDLogFlag.verbose.rawValue) != 0 {
    ...
}

Upvotes: 3

Related Questions