swiftcocoalumberjack

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?


Solution

  • 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.