How to redefine clog to tee to original clog and a log file?

前端 未结 4 673
鱼传尺愫
鱼传尺愫 2020-12-17 04:17

I saw a useful start here:

http://www.cs.technion.ac.il/~imaman/programs/teestream.html

And it works great to make a new stream which goes to both clog and a

4条回答
  •  旧时难觅i
    2020-12-17 04:58

    I would just use the Boost iostreams stuff to do it.

    #include
    #include
    #include
    #include

    int main(const int a_argc, const char *a_args[])
    {
        namespace io = boost::iostreams;
        typedef io::tee_device TeeDevice;
        typedef io::stream TeeStream;
    
        std::ofstream flog("logFile.txt");
        //We need to copy clog, otherwise we get infinite recursion
        //later on when we reassign clog's rdbuf.
        std::ostream clogCopy(std::clog.rdbuf());
    
        TeeDevice logTee(flog, clogCopy);
        TeeStream logTeeStream(logTee);
    
        logTeeStream << "This text gets clogged and flogged." << std::endl;
    
        //Modify clog to automatically go through the tee.
        std::streambuf *originalRdBuf = std::clog.rdbuf(logTeeStream.rdbuf());  
    
        std::clog << "This text doesn't only get clogged, it's flogged too." << std::endl;
    
        std::clog.rdbuf(originalRdBuf);
        std::clog << "This text avoids flogging." << std::endl;
    }
    

提交回复
热议问题