0

I have built LOG4CXX lib and DLL and trying to use it in my application

Loh.h 
class Log
{
public:
 Log(void);
 ~Log(void);
 void Debug(const char *msg);

private:
static LoggerPtr  oLogger;
};

Log.cpp
LoggerPtr  oLogger = NULL;
Log::Log()
{
        LoggerPtr oLogger(Logger::getLogger("Test"));
    PropertyConfigurator::configure("Logger4CXX.properties");
}

void CLogger::Debug(const char *msg)
{
    if(oLogger != NULL)
    {
        LOG4CXX_DEBUG(oLogger,"Testing application...");    
    }
}

In my main I am initializing Log class object and calling Debug method to log debug message to a file.

Issue I am facing is at if(oLogger != NULL) which is always returning oLogger as NULL.

Can anyone offer any help on this.

user987316
  • 894
  • 4
  • 13
  • 35

1 Answers1

0

In your constructor you create new local (method-wide) variable named oLogger which shadows the class variable of the same name. This should do the trick:

Log::Log()
{
    oLogger = new LoggerPtr(Logger::getLogger("Test"));
    PropertyConfigurator::configure("Logger4CXX.properties");
}

This local variable gets destroyed when it goes out of scope (when the method ends).

Edit : As for your comment with "not liking pointers". You can dereference it with *oLogger, or to avoid using a pointer, you can simply skip the new keyword.

Edit2: This should be the safest way, without statics and keeping LoggerPtr as you have it :

Log::Log() : oLogger(LoggerPtr(Logger::getLogger("Test"))
{
    PropertyConfigurator::configure("Logger4CXX.properties");
}

This is called an initializer list.

Losiowaty
  • 7,911
  • 2
  • 32
  • 47
  • this may solve my problem with oLogger becoming NULL. But it requires oLogger to be defined as static LoggerPtr *oLogger; and LOG4CXX_DEBUG method does not likes pointered oLogger. Any other options? – user987316 Nov 18 '13 at 09:29
  • Well, after a second look at your code, it seems that there are two classes there : `Log` and `CLogger`. In this case accessing the `Log::oLogger` variable from CLogger class method without an instance of `Log` would require this. Though I'm not certain if this is what you want, as you mix classes in your code which makes it harder to understand. – Losiowaty Nov 18 '13 at 09:32
  • I have removed confusing part from code snippet. It is now in a exact state I am using it. Loggerptr is a Log4CXX object pointer , whose DLL I have used for referencing. – user987316 Nov 18 '13 at 09:37
  • I resolved the issue by initializing oLogger globally instead in constructor. – user987316 Nov 18 '13 at 09:42