c++dlllog4cplus

How to use Log4Cplus in DLL


What is the best practice to use Log4Cplus in a DLL ?

I want to use a FileAppender.

I have a win32 DLL, that has DLLMain, and 3 exported Function.

Where do I define the Appender and Layout object ? Where to set their properties ? Where do I link them to a logger ?

I want to use the logger in all classes inside the dll I guess by just calling:

Logger myLogger= Logger::getInstance("myLoggerName");

where should I put the code so I can have the log4cplus macros enabled and working in all my functions inside the dll ?

In a normal program I will use global variables, use main or some ctor to set them up and then everything can see them. What do I do inside a dll ?

(I don't want to call the setup code in every exported function, but only once when dll is loaded)


Solution

  • Where do I define the Appender and Layout object? Where to set their properties? Where do I link them to a logger?

    Generally, I think that your DLL should have some MyDLLInit() function that you can call that would configure log4cplus according to your needs.

    Where should I put the code so I can have the log4cplus macros enabled and working in all my functions inside the DLL?

    You should not need to do anything special here. Just include the loggingmacros.h to get the macros and use them.

    In a normal program I will use global variables, use main or some ctor to set them up and then everything can see them. What do I do inside a DLL?

    It seems to me that using a global Logger instance (that would be initialized by your MyDLLInit() function) is OK. But if your DLL has some kind of "context" handle that it returns to its users, use that instead and stick the Logger instance into the "context" handle instead.

    (I don't want to call the setup code in every exported function, but only once when dll is loaded)

    This should not be necessary.

    See the tests sources that are part of the source distribution, use them as examples of how you can instantiate Appender and Layout. E.g., fileappender_test

    UPDATE

    You do not have to keep either the Appender or the Layout in any of your own variables. Both are managed by log4cplus. After you do logger.addAppender(myappender) (corresponding to line 23 in the fileappender_test linked above), all of the variables including myappender can get out of scope and can be destroyed because the Appender is managed by the Logger and Appender's layout is managed by the Appender.