自定义流到C ++中的方法? [英] Custom stream to method in C++?
问题描述
我正在做一个记录器,我希望有一些流类似的事情发生,理想情况下做 CLogger< 测试,< 1<< ,2,3\\\
而不是
; CLogger-> log(Testing,%i,2,3,1);
I'm making a logger and I wish to have some kind of stream-like happenings going on, ideally doing CLogger << "Testing, " << 1 << ",2,3\n";
instead of CLogger->log("Testing, %i,2,3", 1);
我的问题是我该怎么做?我不想直接创建一个流到stdout,因为我想使用我自己的方法,其中包括写入文件等。我考虑过重载一个特定的结构,将冲洗当前流缓冲区一个方法,但我必须做 CLogger<<冲洗
My question is how would I do this? I don't want to directly create a stream to stdout as I want to use my own method which includes writing files and such. I've considered overloading with a certain struct that'd flush the current stream buffer to a method, but I'd have to do CLogger << flush << "Test!\n";
which is kind of odd.
有没有人知道怎么做?
推荐答案
如果你需要的是将某些日志消息定向到文件,你是否考虑过 std :: ofstream
If all that you need is directing certain log messages to files, have you considered std::ofstream
?
否则,我喜欢从 std :: ostream
派生我的日志类,的流良好。诀窍是将所有应用程序特定的代码放在相关的streambuf类中。考虑:
Otherwise, I like to derive my logging class from std::ostream
, so I get all of the stream goodness. The trick is to put all of your application-specific code in the associated streambuf class. Consider:
#include <iostream>
#include <sstream>
class CLogger : public std::ostream {
private:
class CLogBuf : public std::stringbuf {
private:
// or whatever you need for your application
std::string m_marker;
public:
CLogBuf(const std::string& marker) : m_marker(marker) { }
~CLogBuf() { pubsync(); }
int sync() {
std::cout << m_marker << ": " << str();
str("");
return std::cout?0:-1;
}
};
public:
// Other constructors could specify filename, etc
// just remember to pass whatever you need to CLogBuf
CLogger(const std::string& marker) : std::ostream(new CLogBuf(marker)) {}
~CLogger() { delete rdbuf(); }
};
int main()
{
CLogger hi("hello");
CLogger bye("goodbye");
hi << "hello, world" << std::endl;
hi << "Oops, forgot to flush.\n";
bye << "goodbye, cruel world\n" << std::flush;
bye << "Cough, cough.\n";
}
注意:
- CLogger构造函数可以接受您需要使用的任何参数 - 文件名,输出语言,指向底层日志数据的指针。
在响应std :: flush时会自动调用CLogBuf的sync()。
- The CLogger constructor can take whatever parameters you need to use -- a filename, an output language, a pointer to the underlying log data, whatever. Just pass the data onto the CLogBuf class.
- The CLogBuf's sync() is automatically called during in response to std::flush.
这篇关于自定义流到C ++中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!