I use cpp under Linux and I want to use the log4cpp.
I have tried to use it under windows with vs2013 and it worked very well. Now I am working under Linux and I got a problem:
It doesn't work with file. Here is my test code:
int main(int argc, char* argv[])
{
fstream logFile;
logFile.open("log", std::ios::app);
log4cpp::OstreamAppender* osAppender = new log4cpp::OstreamAppender("osAppender", &logFile);
// I tried cout as below and it worked, but if I tried as above with a file, it didn't work anymore.
// I mean the "log" file could be created but the message can't be written down in the file. The file is always empty.
//log4cpp::OstreamAppender* osAppender = new log4cpp::OstreamAppender("osAppender", &cout);
osAppender->setLayout(new log4cpp::BasicLayout());
log4cpp::Category& root = log4cpp::Category::getRoot();
root.addAppender(osAppender);
root.setPriority(log4cpp::Priority::DEBUG);
root.error("Hello log4cpp in aError Message!");
root.warn("Hello log4cpp in aWarning Message!");
log4cpp::Category::shutdown();
cout<<"test";
return 0;
}
I ran this test code many times, I got no error and the program finished successfully because I can see "test" at the console. But the file is always empty.
By the way, sudo chmod +777 log
has been done. So it couldn't be the problem of permission.
The problem is here:
fstream logFile;
logFile.open("log", std::ios::app);
What I need is:
If there is no file, create it and write message in it;
If there has been the file, apprend the message in it.
To achieve this goal, we have two ways:
ofstream logFile;
logFile.open("log", std::ios::app);
OR
fstream logFile;
logFile.open("log", std::ios::app | std::ios::out);