Click here to Skip to main content
15,893,564 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Following is my code:
C++
class LogCp
{
public:

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

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

};

C++
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 func:
C++
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?

What I have tried:

read lots of similar questions but still cannot resolve this
Posted
Updated 25-Nov-16 1:02am

1 solution

The scope or lifetime of your LogCp doesnt cover the main scope. It is essential to understand that issues. It is also very important if working with pointers and objects.

This should solve your problem:

C++
int main(int argc, wchar_t* argv[])
{
	LogCp::GetInstance();// create in scope of main
	// your code
	LOG4CPLUS_WARN(LogCp::GetInstance()._logger, LOG4CPLUS_TEXT("test"));
}
 
Share this answer
 
Comments
TimGallin 27-Nov-16 22:07pm    
It doesn't work,I have to call doConfigure() function again in main(),in Getinstance() function,I return a static object vLogCp,its lifetime should be the whole process,and the static member variable of vLogCp has be initialed in the constructor func,which include the doConfigure() already,so why I still have to call the doConfigure agian in main()?
Following is my config text:
log4cplus.appender.R=log4cplus::RollingFileAppender
log4cplus.appender.R.File=output_${ENV_VAR}.log
log4cplus.appender.R.MaxFileSize=500KB
log4cplus.appender.R.MaxBackupIndex=5
log4cplus.appender.R.layout=log4cplus::TTCCLayout

log4cplus.rootLogger=INFO, R
log4cplus.logger.test.a.b.c=WARN
log4cplus.logger.filelogger=WARN, R
log4cplus.additivity.filelogger=FALSE

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900