我想要创建一个通用日志文件,可以轻松地在多个文件中重用。此外,我希望能够使用通用的std::cout,这样我就可以轻松地编写格式化的文本(与创建我自己的写函数相反,它可能只写字符串,而且可能永远不会如此通用)。
定义
#include <fstream>
class logstream :
public std::ofstream
{
public:
logstream();
~logstream();
protected:
std::streambuf *psbuf, *backup;
std::ofstream filestr;
};实现
logstream::logstream()
{
filestr.open("test_streaming.txt", std::ofstream::app);
backup = std::clog.rdbuf(); // back up cout's streambuf
psbuf = filestr.rdbuf(); // get file's streambuf
std::clog.rdbuf(psbuf); // assign streambuf to cout
}
logstream::~logstream()
{
std::clog.rdbuf(backup); // restore cout's original streambuf
filestr.close();
}用法:
void CExportDlg::OnBnClickedButtonLog()
{
logstream log; // redirects clog and restores it when it goes out of scope
std::clog << "hello this goes into log file" << std::endl;
std::clog << "And I can readily write intetgers like " << 5 << "this one" << std::endl;
}实际上,我已经将行logstream log放在主应用程序类中,所以现在我只能在应用程序中的任何地方使用std:clog(),并且输出到日志文件。但这是否可以改善呢?
如果我想为不同的目的创建多个日志文件怎么办?是否有一种方法可以通过对象访问clog() (或cout()),使其只进入该对象,比如log.clog()?
发布于 2016-12-21 01:31:10
我喜欢您使用现有的流API而不是滚动自己的流API。另外,我认为重定向std::clog是一种很好的方法,因为这可以很容易地重新安装到正确使用std::clog的现有应用程序中。
然而,也存在一些问题。
from std::ofstream的继承意味着这样的用法:
logstream log("logfile.txt");
log<<"foobar\n";但这不是该类的预期用法。我也看不出为什么这个类必须继承std::ofstream。我会删除这个继承,因为我认为它破坏了Liskov代换原理。
虽然范围设计在某些/许多情况下是好的,但我不认为这是其中之一。通常,日志目标不是为每个作用域配置的,而是为应用程序配置一次。这只是个人意见,我相信这是有其用途的。
我错过了一些特征。想到的一个特别之处是同时写入文件和控制台(如@LokiAstari 这里的例子)。
例如,log4cpp,它提供日志流,您可以将std::clog重定向到并单独使用。它是可配置的,并拥有您通常希望从日志系统中得到的所有提示。
https://codereview.stackexchange.com/questions/150433
复制相似问题