首页 > 解决方案 > 如何编写在 C++ 中进行实际记录的可变参数记录器函数

问题描述

我正在用 C++ 编写一个记录器类我想将所有日志从不同的文件重定向到一个决定在哪里写入日志的函数。

例如,

func A()
{
int a =10;
std::string b = "test";
cout<<"printing"<<a<<b<<endl;
}

func B()
{
unsigned long t = 6700;
cout<<t<<endl;
}

而不是 cout 我想要一个函数,它接受可变参数并发送到最终打印或写入文件或使用 syslog 的公共函数。

标签: c++logging

解决方案


如果你尝试一些简单的东西,像这样呢?

std::unique_ptr<std::ostream> g_ostream_ptr;


std::ostream& log() {
    return *g_ostream_ptr;
}

void initialize_log() { 
    // initialize `g_ostream_ptr` based on environment variable
    // or other configuration information.
    const char* filename = std::getenv("LOG_FILE");
    if (!filename)
        filename = "/dev/stdout"

    g_ostream_ptr = std::make_unique<std::ostream>(filename);
}

然后你可以像这样使用它:

void f() {
    log() << “f called.” << std::endl;
}

您必须确保initialize_log在某个时候调用它,可能是使用std::call_once,或者可能只是在 中调用它main()


推荐阅读