Search code examples
c++ostream

How to implement a logging macro with automatic newline in C++


In the C++ library glog (Google logging module) there is a nice interface where you can write

LOG(INFO) << "abc " << my_var;

and at runtime it prints something like abc 5\n at runtime (if my_var was 5) where it automatically terminated with a newline.

This is much superior to having to always terminate with std::endl as in

std::cout << "abc " << my_var << std::endl;

What is the simpliest way (code + macros) do I need to replicate this effect in my code?


Solution

  • I think the idea is to return a temp wrapper object:

    #include <iostream>
    
    struct Log
    {
        ~Log(void) { ::std::cout << ::std::endl; }
    };
    
    template<typename T> Log &&
    operator <<(Log && wrap, T const & whatever)
    {
        ::std::cout << whatever;
        return ::std::move(wrap);
    }
    
    int main()
    {
        Log() << "whatever";
        Log() << "more";
        return 0;
    }
    

    online compiler

    Note that the macro can be used here to execute conditional branching in the beginning of logging. That is skip logging if severity level is low.

    #define LOG(level) \
        if(g_log_lelevel <= level) Log()