c++ostreamstreambuf

Create a logging object with std::stream interface


Internally we have a logging function with the interface OurLog(const char *). I'd like to be able to use it with an interface similar to std::ostringstream. In other words, I'd love to have an adaptor object so I can write:

 logging_class log;
 log << "There are " << num_lights << " lights\n";

And this call OurLog() as necessary to write the message to the log.

It looks like making buffer class derived from std::streambuf is the right way to go; how does one go about this? What functions need to be implemented?


Solution

  • Found a simple example in the libstdc++ documentation here.

    class LoggingBuffer : public std::streambuf {
    protected:
        virtual int_type overflow (int_type c) {
            if (c != EOF) {
                char msg[2] = {static_cast<char>(c), 0};
                OurLog(msg);
            }
            return c;
        }
    };
    
    class Logger : public std::ostream {
        LoggingBuffer logging_buffer;
    public:
        Logger() : logging_buffer(), std::ostream(&logging_buffer) {}
    
    };
    
    extern Logger log; //instantiated in a cpp file for global use
    

    Unfortunately it doesn't look very performant, since it requires a function call for every single character. Is there a more efficient way of doing this?