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

前端 未结 4 658
鱼传尺愫
鱼传尺愫 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条回答
  •  暖寄归人
    2020-12-17 05:00

    Here is the class I created that seems to do the job, thanks to all who helped out!

    -William

    class TeeStream : public std::basic_filebuf >
    {
    private:
      class FileStream : public std::ofstream {
      public:
        FileStream()
          : logFileName("/my/log/file/location.log") {
          open(logFileName.c_str(), ios::out | ios::trunc);
    
          if (fail()) {
            cerr << "Error: failed to open log file: " << logFileName << endl;
            exit(1);
          }
        }
        ~FileStream() {
          close();
        }
    
        const char *getLogFileName() const {
          return logFileName.c_str();
        }
    
      private:
        const string logFileName;
    
      };
    
    public:
      typedef std::char_traits traits;
      typedef std::basic_filebuf baseClass;
    
      TeeStream()
        :  baseClass(),
           _logOutputStream(),
           _clogBuf(clog.rdbuf()),
           _fileBuf(_logOutputStream.rdbuf()) {
        clog.rdbuf(this);
        _logOutputStream << "Log file starts here:" << endl;
      }
      ~TeeStream() {
        clog.rdbuf(_clogBuf);
      }
    
      int_type overflow(char_type additionalChar =traits::eof()) {
        const int_type eof = traits::eof();
        const char_type additionalCharacter = traits::to_char_type(additionalChar);
        const int_type result1 = _clogBuf->sputc(additionalCharacter);
        const int_type result2 = _fileBuf->sputc(additionalCharacter);
    
        if (traits::eq_int_type(eof, result1)) {
          return eof;
        } else {
          return result2;
        }
      }
    
      int sync() {
        const int result1 = _clogBuf->pubsync();
        const int result2 = _fileBuf->pubsync();
    
        if (result1 == -1) {
          return -1;
        } else {
          return result2;
        }
      }
    
    private:
      FileStream _logOutputStream;
      streambuf * const _clogBuf;
      streambuf * const _fileBuf;
    
    };
    

提交回复
热议问题