使用std :: cout添加时间戳 [英] Add time stamp with std::cout

查看:404
本文介绍了使用std :: cout添加时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,它将我的 std :: cout 输出重定向到日志文件。

I have the following code which is redirecting my std::cout output to a log file.

std::ofstream out("out.txt");
std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!

现在我想要的是,每当换行符发生时, / strong>将被写入文件。

Now what I want is that whenever a newline is occurring, then the current time stamp will be written to the file.

我知道我可以使用:

std::cout << getTime() << "printing data" << std::endl;

但我想要的是 std :: cout 自动地照顾它。这是可能的吗?

But what I want is that of std::cout taking care of it automatically somehow. Is that possible?

推荐答案

我假设你想打印时间戳,如果下一行的第一个字符出现在输出。
获取一个新类,并从std :: streambuf继承它,并以与使用filebuf相同的方式连接它。如果出现newline-charater,则在该对象中存储此事件。显示另一个字符将时间戳添加到流。

I assume, that You want print the TimeStamp, if the first character of the next line appears in the output. Take a new class and inherit it from std::streambuf and connect it in the same way You do with the filebuf. If a newline-charater appears store this event in the object. Appears another character add the timestamp to the stream.

我写了一个使用RAII成语连接streambuf的示例。

I wrote an example which use the RAII idiom for connecting the streambuf.

class AddTimeStamp : public std::streambuf
{
public:
    AddTimeStamp( std::basic_ios< char >& out )
        : out_( out )
        , sink_()
        , newline_( true )
    {
        sink_ = out_.rdbuf( this );
        assert( sink_ );
    }
    ~AddTimeStamp()
    {
        out_.rdbuf( sink_ );
    }
protected:
    int_type overflow( int_type m = traits_type::eof() )
    {
        if( traits_type::eq_int_type( m, traits_type::eof() ) )
            return sink_->pubsync() == -1 ? m: traits_type::not_eof(m);
        if( newline_ )
        {   // --   add timestamp here
            std::ostream str( sink_ );
            if( !(str << getTime()) ) // add perhaps a seperator " "
                return traits_type::eof(); // Error
        }
        newline_ = traits_type::to_char_type( m ) == '\n';
        return sink_->sputc( m );
    }
private:
    AddTimeStamp( const AddTimeStamp& );
    AddTimeStamp& operator=( const AddTimeStamp& ); // not copyable
    // --   Members
    std::basic_ios< char >& out_;
    std::streambuf* sink_;
    bool newline_;
};

以下列方式调用此类的对象:

call an object of this class in following way:

// some initialisation ..
{
    AddTimeStamp ats( cout ); // timestamp is active
    // every output to 'cout' will start with a 'getTime()' now
    // ...
} // restore the old streambuf in the destructor of AddTimeStamp

这篇关于使用std :: cout添加时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆