The simplest way is to imherit std::streambuf and override just two methods:
std::streamsize xsputn(const char_type* s, std::streamsize n)– to append a given buffer with size provided to your internalstd::stringfor exampleint_type overflow(int_type c)to append a singlecharto your internal buffer.
Your streambuf can be construncted from whatever you want (DB connection for example). After append something into the internal buffer you may try to split it into lines and push something into DB (or just buffer an SQL statements to execute later).
To use it just attach your streambuf to any std::ostream using constructor or imbue() rigth after creation.
Simple! I've done something like this to output strings to syslog – everything works fine with any custom operator<< for user defined classes.