我在Linux下使用cpp,我想使用log4cpp。
我尝试过在windows下用vs2013使用,效果很好。现在我在Linux下工作,遇到了一个问题:
它不适用于文件。这是我的测试代码:
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;
}
我多次运行此测试代码,没有出现错误,并且程序成功完成,因为我可以在控制台上看到“test”。但文件始终是空的。
顺便说一句,sudo chmod +777 log
已经完成。所以不可能是权限问题。
最佳答案
问题出在这里:
fstream logFile;
logFile.open("log", std::ios::app);
我需要的是:
如果没有文件,则创建一个文件并在其中写入消息;
如果已有该文件,则将消息追加到其中。
为了实现这一目标,我们有两种方法:
ofstream logFile;
logFile.open("log", std::ios::app);
或者
fstream logFile;
logFile.open("log", std::ios::app | std::ios::out);
关于c++ - log4cpp(Linux): can't write message into logfile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29848076/