c++log4cplus

How to use log4cplus in a custom singleton class


I configure this log4cplus' static object in my custom class LogCp's constructor function,and in this constructor I do write some test code and it can export the informations to a designated file correctly,but when I call the GetInstance fun ction,which will return the only object,it can't write the log and the error message is cannot find the appender of filelogger.It confuse me,I had called the doConfigure() in constructor and the logger had been configured correctly,why I still got this error in main function?Do I need to call doConfigure() everytime before I write log? Following is my code:

class LogCp
{
public:

    ~LogCp();
    static LogCp& GetInstance();
    static Logger _logger;

private:
    LogCp();
    LogCp(const LogCp&) = delete;
    void operator =(LogCp const&);

};

Logger LogCp::_logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("filelogger"));
//Logger LogCp::_logger = log4cplus::Logger::getRoot(); 

LogCp::LogCp()
{
    log4cplus::Initializer initializer;
    try {
        PropertyConfigurator::doConfigure(LOG4CPLUS_TEXT("E:\\log4cplus.properties"));
        //_logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("filelogger"));
        LOG4CPLUS_WARN(_logger, LOG4CPLUS_TEXT("logging...."));
    }
    catch (...) {
        LOG4CPLUS_FATAL(_logger, LOG4CPLUS_TEXT("Exception occured..."));
    }
}

LogCp& LogCp::GetInstance()
{
    static LogCp vLogCp;
    return vLogCp;
}

LogCp::~LogCp()
{

}

the main function:

void logInitial()
{
    LogCp::GetInstance();

}

int main(int argc, wchar_t* argv[])
{
    logInitial();
    LOG4CPLUS_WARN(LogCp::GetInstance()._logger, LOG4CPLUS_TEXT("test"));
}

It can log correctly in constructor function,but it won't log "test" in main() function unless I add doConfigure() function again before LOG4CPLUS_WARN.why?


Solution

  • You need to configure the library before you try to use it. The doConfigure() function sets up appenders without which there will be no output.

    Using log4cplus::Initializer initializer; in your ctor is wrong. It will initialize the library and deinitialize it at the end of the constructor. The initializer object must live throughout the use of the library.