使用ostream的C ++日志记录 [英] C++ logging using ostream

查看:132
本文介绍了使用ostream的C ++日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做记录器。我想创建一个以流作为输入的函数 log()

I'm making a logger. I want to create a function log() that takes a stream as input.

例如:

log("hello"<<" "<<"world"<<10<<"\n");

我也希望它是线程安全的。

I also want it to be thread safe.

我已重新定义<< <$ / code>运算符,因此我可以:

I've redefined the << operator so I can do:

log()<<"hello"<<"world"<<10<<"\n"

但是此操作不是线程安全的。

But this operation is not thread safe.

如何使线程安全?

推荐答案

log()返回一个缓冲内存中所有输出的临时对象。该对象的析构函数将在表达式的末尾运行,并且应该在单个原子操作中将累积的数据刷新到实际流中(直到你使该操作是原子的)。

Have log() return a temporary object that buffers all output in memory. The destructor for this object will run at the end of the expression, and should flush the accumulated data to the actual stream in a single atomic operation (up to you to make that operation atomic).

这将使你的第二个语法可行:

That will make your second syntax feasible:

log()<<"hello"<<"world"<<10<<"\n";

这篇关于使用ostream的C ++日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆