C++ logging using ostream

2019-02-20 19:46发布

问题:

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?

回答1:

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";


回答2:

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.



回答3:

in C++03 all operations are not thread safe



标签: c++ stream