c++中自定义日志的方法
Ways for custom logging in C++
我正在重构我的一个c++应用程序。在我使用像
这样的宏之前LOG("something interesting") // 1
LOG("something ended") // 2
LOG("foo: " << bar) // 3
我现在的想法是写一个Log
类,像这样:
Log(std::string _init_message):
init_message(_init_message)
{ PrintLogLine(init_message + " ...");}
~Log()
{ PrintLogLine(init_message + " done.");}
当我像
那样使用它时,获得特定动作的"自动"记录(即当它们开始,停止+额外的计时等)。
void ActionXYZ() {
Log log("xyz");
// do stuff
}
我正在努力的地方是在定义一种方法,使它的工作情况3)。在Java中,我可以使用一个方法,它需要一个String
参数,因为编译器会自动处理字符串构建。c++中有哪些可能性?
我可以使它工作,以便我可以像使用一个选项一样使用它吗?
// in "do stuff"
log("foo:" + bar); // OR
log << "foo:" << bar;
正如我在评论中提到的,您可以使用Boost.Format。它还有助于解决int-to-string转换等问题。这可能会变得有点冗长,但是—为了避免调用.str()
来调用std::string
构造函数,您可以创建一个直接接受boost::format
的构造函数。
Log log(boost::format("foo %1% bar") % 42); // with Log(boost::format)
Log log((boost::format("foo %1% bar") % 42).str()); // with only Log(std::string)
参考Boost。
我立刻想到了两种可能。第一种是利用std::string附加:
Log log(std::string("foo:") + bar);
第二种是创建更多的log
构造函数,这些构造函数接受额外的形参:
Log log("foo:", bar);
您确实应该考虑使用Boost.Log进行日志记录。日志记录可能是一件复杂的事情;得到一个完全形成的实现是很有用的。
你可以创建一个从std::strstream继承的日志类。
class Mstream : public std::strstream
{
public:
Mstream() : std::strstream(Buffer = new char[BUFLEN], BUFLEN, ios::out);
ostream& endf(ostream& s);
void Write();
private:
char* Buffer;
};
现在您可以将输出记录为
Mstream m;
m <<"Foo"<<s<<endf;
endf (ostream&5)你可以将ostream转换为Mstream并调用Write()。在Write()中,格式化输出并将其打印到控制台或文件中。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 调用静态记录器的格式日志方法
- 日志C 类方法呼叫者(功能名称,行号)
- 执行调试日志记录的更好方法
- 在 C++11 应用程序中进行错误日志记录的优雅方法
- 使用c++进行日志本地化的最佳方法
- 如何使用log4cplus在日志文件中打印方法名称
- c++中自定义日志的方法
- 日志系统应该使用哪种输出方法