Eliza Wilson
Eliza Wilson

Reputation: 1101

How do you use Lumberjack logging in Swift?

I'm in the process of converting an Objective-C file which uses Lumberjack Logging into Swift. It seems to be mostly working, except for the part where I declare ddloglevel.

The Objective-C way to do this:

#ifdef DEBUG
static const int ddLogLevel = LOG_LEVEL_INFO;
#else
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#endif

The Swift way:

#if DEBUG
let ddLogLevel = LOG_LEVEL_INFO;
#else
let ddLogLevel = LOG_LEVEL_VERBOSE;
#endif

Except I'm this compile time error: Use of unresolved identifier 'LOG_LEVEL_INFO'

Why is this happening? How can I fix it?

Upvotes: 3

Views: 3150

Answers (2)

Marek Gregor
Marek Gregor

Reputation: 3851

You can use workaround. Instead of setting logLevel globally (possible only in Objective-C), you could set logging level to all Loggers explicitly. Example:

class LoggerFactory {
#if DEBUG
  static let defaultLogLevel: DDLogLevel = DDLogLevel.All
#else
  static let defaultLogLevel: DDLogLevel = DDLogLevel.Info
#endif

static func initLogging() {
  DDLog.addLogger(DDTTYLogger.sharedInstance(), withLevel: defaultLogLevel)
  DDLog.addLogger(DDASLLogger.sharedInstance(), withLevel: defaultLogLevel)
}

Upvotes: 8

Bill
Bill

Reputation: 45465

Looking at the library source, LOG_LEVEL_INFO and LOG_LEVEL_VERBOSE are #define macros, which Swift does not automatically import. Swift only sees const's.

However, I think that your approach as a whole might not make sense - it looks like you're trying to assign a value to the global Objective-C constant ddLogLevel. Swift's let is not going to do that for you - it's a completely different namespace. This is on top of not being able to use Objective-C macros in Swift.

Your best bet is to leave an Objective-C file in your project (called, say, LoggingConfig.m that just contains:

#import "DDLog.h"

#ifdef DEBUG
static const int ddLogLevel = LOG_LEVEL_INFO;
#else
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#endif

The library you're using relies heavily on Objective-C features, so best to just use Objective-C to configure it.

Edit: Looking at this library in more detail (I'd never heard of it before), using CocoaLumberjack at all in Swift is probably not going to work out, as its primary API is a preprocessor macro named DDLog. I don't think it's a good match.

Upvotes: 2

Related Questions