log4cpp(linux):无法将消息写入logfile

时间:2015-04-24 12:54:03

标签: c++ linux log4cpp

我在Linux下使用cpp,我想使用log4cpp。

我试过在vs2013的windows下使用它,它运行得很好。现在我在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;
}

我多次运行此测试代码,没有错误,程序成功完成,因为我可以看到&#34; test&#34;在控制台。但是文件总是空的。

顺便说一下,sudo chmod +777 log已经完成了。所以它不会成为许可问题。

1 个答案:

答案 0 :(得分:2)

问题在于:

 fstream logFile;
 logFile.open("log", std::ios::app);

我需要的是:
如果没有文件,请创建它并在其中写入消息;
如果有文件,请在其中添加消息。

为实现这一目标,我们有两种方式:

 ofstream logFile;
 logFile.open("log", std::ios::app);

OR

 fstream logFile;
 logFile.open("log", std::ios::app | std::ios::out);