如何编写具有cout样式界面的记录器类(记录器<<"错误:"<< val<< endl;) [英] how do I write a logger class with cout style interface (logger << "Error: " << val << endl;)

查看:142
本文介绍了如何编写具有cout样式界面的记录器类(记录器<<"错误:"<< val<< endl;)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个记录器类,使其具有如下功能:

I want to create a logger class such that with a functionality like this:

Logger log;
log << "Error: " << value << "seen" << endl;

这应该为我打印一条自定义格式的消息.例如. "12-09-2009 11:22:33看到错误5"

This should print me a custom formatted message. E.g. "12-09-2009 11:22:33 Error 5 seen"

我的简单课程目前看起来像这样:

My simple class currently looks like this:

class Logger {
    private:
        ostringstream oss;
    public:
        template <typename T>
        Logger& operator<<(T a);
}

template <typename T>
Logger& Logger::operator<<(T a) {
    oss << a;
    return *this;
}

void functionTest(void) {
    Logger log;
    log << "Error: " << 5 << " seen";
}

这将导致oss正确拥有缓冲区错误:5见".但是我不知道我还需要编写/修改什么其他功能才能在屏幕上打印出一些东西. 有谁知道如何使它正常工作,或者还有另一种方法来设计此类以使我的功能正常工作吗?

This will cause oss to correctly have the buffer "Error: 5 seen". But I dont know what other function I need to write/modify so that something prints on the screen. Does anyone know how to get this to work or is there another way to design this class to have my functionality work?

推荐答案

每个std::ostream后面都是一个streambuf.可以通过std::stream::rdbuf()对其进行检索和设置.特别是,它可以包装-您可以提供一个streambuf对象,该对象可以对流文本进行后处理. (后处理意味着您无法区分std::cout << 123;std::cout << "123";)

Behind every std::ostream is a streambuf. It cab be retrieved and set via std::stream::rdbuf(). In particular, it can be wrapped - you can provide a streambuf object that post-processes the streamed text. (post-processing means you can't distinguish std::cout << 123; from std::cout << "123"; )

在您的特定情况下,后处理非常简单.在每一行的开头,您要插入一些字节.这仅意味着您应该跟踪是否已经输出了当前行的前缀.如果不是,请这样做并设置标志.并且,每当您看到换行符时,都将其重置.您的streambuf包装器只有一个bool值的状态.

In your particular case, the postprocessing is fairly simple. At the start of every line you want to insert some bytes. This merely means that you should keep track of whether you've already output the prefix for the current line. If not, do so and set the flag. And whenever you see a newline, reset it. Your streambuf wrapper has just a single bool worth of state.

这篇关于如何编写具有cout样式界面的记录器类(记录器&lt;&lt;&quot;错误:&quot;&lt;&lt; val&lt;&lt; endl;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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