iosswiftloggingcocoalumberjack

CocoaLumberjack with Swift - Calling preprocessor macros


I started to build an IOS app with the new programming language Swift. I managed to use CocoaPods and was able to successfully create the DDTTYLogger with my CustomLoggerFormatter (Objective-C) in my AppDelegate.swift and append it to the loggers.

var customLoggerFormatter = CustomLoggerFormatter()

var consoleLogger: DDTTYLogger = DDTTYLogger.sharedInstance()
consoleLogger.setLogFormatter(customLoggerFormatter)
DDLog.addLogger(consoleLogger)

But the problem is, that the CocoaLumberjack Library is using preprocessor macros for the logger methods like DDLogVerbose(@"..")

Which is defined in the DDLog.h:

#define DDLogVerbose(frmt, ...) LOG_OBJC_MAYBE(LOG_ASYNC_VERBOSE, LOG_LEVEL_DEF, LOG_FLAG_VERBOSE, 0, frmt, ##__VA_ARGS__)

Is there any workaround to make preprocessor defines work in Swift? Or did anyone try something similar with more success?


Solution

  • Okay, I just found a solution. Writing an Objective-C Wrapper class calling the preprocessors and offering methods to call it.

    Hopefully this will help other people facing the same issues.

    I first created a header file:

    @interface DDLogWrapper : NSObject
    + (void) logVerbose:(NSString *)message;
    + (void) logError:(NSString *)message;
    + (void) logInfo:(NSString *)message;
    @end
    

    With the corresponding implementation:

    #import <Foundation/Foundation.h>
    #import "DDLogWrapper.h"
    
    // Logging Framework Lumberjack
    #import "DDLog.h"
    #import "DDASLLogger.h"
    #import "DDTTYLogger.h"
    
    // Definition of the current log level
    #ifdef DEBUG
    static const int ddLogLevel = LOG_LEVEL_VERBOSE;
    #else
    static const int ddLogLevel = LOG_LEVEL_ERROR;
    #endif
    
    @implementation DDLogWrapper
    
    + (void) logVerbose:(NSString *)message {
        DDLogVerbose(message);
    }
    
    + (void) logError:(NSString *)message {
        DDLogError(message);
    }
    
    + (void) logInfo:(NSString *)message {
        DDLogInfo(message);
    }
    
    @end
    

    Important is to add the DDLogWrapper.h File to the ProjectName-Bridging-Header.h file and then you are able to instantiate in Swift the DDLogWrapper and call the methods logVerbose, logError, logInfo..

    With the following code I was able to make a log statement:

    DDLogWrapper.logVerbose("TEST");