C++ logging using ostream

前端 未结 3 1670
鱼传尺愫
鱼传尺愫 2021-01-17 04:02

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

For instance:

log(\"hello\"<<\" \"<<\"         


        
相关标签:
3条回答
  • 2021-01-17 04:52

    in C++03 all operations are not thread safe

    0 讨论(0)
  • 2021-01-17 04:59

    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";
    
    0 讨论(0)
  • 2021-01-17 05:04

    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.

    0 讨论(0)
提交回复
热议问题