c++ - 如何编写在 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 的公共函数。
解决方案
如果你尝试一些简单的东西,像这样呢?
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()
。
推荐阅读
- r - 如何修复 Sweave 中代码的位置?
- jsf - 将 ui:includes 重构为 ui:components
- xamarin.forms - 列表视图xamarin表单内网格内的图像问题
- excel - excel(vba)中的日志功能 - 没有给我正确的答案
- node.js - 为什么在某些情况下 res 未定义?
- audio - 录制 nativescript 时忽略手机的输出
- javascript - Google 表格/Javascript 粘贴问题
- react-native - 滚动列表时将本机滚动反应到偏移量
- java - Spring JPA - 将列映射到双精度或浮点数?
- python - python (hmmlearn) 中的隐马尔可夫模型 (HMM) 总是预测时间序列的相同值