c ++日志异常到文件,输出不同

时间:2014-02-13 14:30:00

标签: c++ exception logging

我想将Exception记录到文件中,并将其发送到控制台。我的问题是我得到了不同的输出。

   
void log(std::string str, std::exception e){
    std::ofstream errorfile;
    errorfile.open("errorlog.txt", std::ios::out | std::ios::app);
    errorfile << str << std::endl;
    errorfile << e.what() << std::endl;
    errorfile.close();
}

main()
{
    try
    {
        doSomething();
    }
    catch(std::exception& e)
    {
        std::string str = "functionname()";
        std::cout << str << std::endl;
        std::cerr << e.what() << std::endl;
        log(str, e);
    }
}

现在我得到一个如下的控制台输出:

fuctionname()
bind: Address already in use

和日志文件中的不同输出:

functionname()
std::exception

我知道我使用std::cerr作为我的控制台输出,但我不知道如何使用std::cerr登录文件。

1 个答案:

答案 0 :(得分:0)

在您的函数void log(std::string str, std::exception e)中,您可以创建例外的副本。

将您的功能修改为void log(std::string &str, std::exception &e)

获取有关此对象的引用以保留相同的异常/消息,而不是创建具有空白字段的新异常消息。

你也可以通过这样做来提高你的表现。