灵活的记录器类使用C ++中的标准流 [英] Flexible logger class using standard streams in C++

查看:128
本文介绍了灵活的记录器类使用C ++中的标准流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个灵活的logger类。我希望它能够将数据输出到文件或标准输出。此外,我想使用流。类应该看起来像:

i would like to create a flexible logger class. I want it to be able to output data to a file or to standard output. Also, i want to use streams. The class should look something like:

class Logger
{
private:
   std::ostream m_out; // or ofstream, iostream? i don't know
public:

   void useFile( std::string fname);
   void useStdOut();

   void log( symbol_id si, int val );
   void log( symbol_id si, std::string str );
   //etc..
};

symbol_id 是一个枚举,格式化。我想要实现的是能够容易地从标准输出切换到文件,反之亦然(这是 use * 方法的目的)。优选地,通过使用 m_out 并且简单地写 m_out<

The symbol_id is an enum and defines the formatting. What i want to achieve is to be able to easily switch from standart output to a file and vice versa (this is the purpose of the use* methods). Preferably by just using m_out and simply writing m_out << "something"; without any checks whether i want to write to a file or stdout.

我知道有很多方法可以用来处理文件或标准输出。 (使用 if的来测试我是否要写入文件或标准输出,C方式(使用 FILE * fprintf ))等等,但我确定必须有一个方法如何实现这个C ++流在一个很好的办法。但我似乎找不到如何做到这一点。有人能帮我吗?

I know there are many ways how to get around this (using if's to test if i want to write to a file or stdout, the "C way" (using FILE* and fprintf)) and so on, but i'm sure there must be a way how to achieve this with C++ streams in a nice way. But i can't seem to find the way how to do it. Can somebody help me please?

推荐答案

我之前攻击这个问题的方式是让 一个抽象基类,并创建单独的 FileLogger OutStreamLogger 类。然后创建一个实现 Logger 接口的 CompositeLogger 对象,它只输出所有记录器:

The way I've attacked this problem before is to make Logger an abstract base class and create separate FileLogger and OutStreamLogger classes. Then create a CompositeLogger object that implements the Logger interface, which just outputs all loggers:

CompositeLogger compLogger;
compLogger.Add(new FileLogger("output.txt"));
compLogger.Add(new StreamLogger(std::cout));
...
compLogger.log(...);

如果你不需要这个级别的灵活性,可以使m_Out变量成为 std :: ostream 的一个指针,并添加一个额外的标志来跟踪是否需要在清理时删除它:

If you don't need this level of flexibility and want to keep all this in a single class you could make the m_Out variable a pointer to std::ostream and add an extra flag to keep track of whether you need to delete it on cleanup:

private:
  std::ostream*   m_out;
  bool            m_OwnsStream;

Logger() {
   m_Out=&std::cout; // defaults to stdout
   m_OwnsStream=false;
}
void useFile(std::string filename) {
  m_Out=new std::ofstream(filename);
  m_OwnsStream=true;
}
~Logger() {
  if (m_OwnStream) 
    delete m_Out; 
}

显然,您需要在 useFile useStdOut 以防止内存泄漏。

Obviously you'd need some more checks in useFile and useStdOut to prevent memory leaks.

这篇关于灵活的记录器类使用C ++中的标准流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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