C++ logging using ostream

2019-02-20 19:54发布

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

For instance:

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

I also want it to be thread safe.

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

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

But this operation is not thread safe.

How can I make it thread safe?

标签: c++ stream
3条回答
三岁会撩人
2楼-- · 2019-02-20 20:09

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";
查看更多
地球回转人心会变
3楼-- · 2019-02-20 20:14

You can't create a function like the one you want. You can, however, create a macro that handles that stuff for you:

// "log" may be defined in the <cmath> header file
// so undefine it if needed
#ifdef log
# undef log
#endif
#define log(stream)          \
    do {                     \
        acquire_lock();      \
        std::cout << stream; \
        release_lock();      \
    } while(0)

You have to change the acquire_lock and release_lock calls to the proper ones for you. And of course use a stream that is appropriate for you as well.

查看更多
时光不老,我们不散
4楼-- · 2019-02-20 20:27

in C++03 all operations are not thread safe

查看更多
登录 后发表回答