如何创建像 std::cout 这样的函数
How to create functions like std::cout?
我正在为我的项目创建自己的日志记录实用程序,我想创建一个像iostream的std::cout这样的函数,以记录到文件并打印到控制台。
这是我想要的:
enum
{
debug, error, warning, info
};
LOG(level) << "test"; // level - from the above enum
结果应该是这样的:
int iPlayerID = 1337;
LOG(info) << "Player " << iPlayerID << "Connected";
[Thu Jan 29 18:32:11 2015] [info] Player 1337 Connected
std::cout
不是一个函数,它是一个 std::ostream
类型的对象,它重载operator<<
。
如何做到这一点的快速草图:
enum Level {
debug, error, warning, info
};
struct Logger {
std::ostream* stream; // set this in a constructor to point
// either to a file or console stream
Level debug_level;
public:
Logger& operator<<(const std::string& msg)
{
*stream << msg; // also print the level etc.
return *this;
}
friend Logger& log(Logger& logger, Level n);
{
logger.debug_level = n;
return logger;
}
};
蚂蚁然后像使用它一样
Logger l;
log(l, debug) << "test";
是让您的LOG(level)
返回一个特殊类型,包含指向std::ostream
的指针,并定义<<
运算符。像这样:
class LogStream
{
std::ostream* myDest;
public:
LogStream( std::ostream* dest ) : myDest( dest ) {}
template <typename T>
LogStream& operator<<( T const& obj )
{
if ( myDest != nullptr ) {
*myDest << obj;
}
return *this;
}
};
LOG(level)
宏创建一个宏的实例,如下所示:
#define LOG(level) LogStream( getLogStream( level, __FILE__, __LINE__ ) )
当然,getLogStream
可以在调用时插入它想要的任何信息(如时间戳)。
您可能希望在 LogStream
的析构函数中添加刷新。
我不会在这里输入编码细节,但我会为您提供一些快速指南:
- 创建一个单例
对象池(对于记录器来说可以创建一个单例)或一个命名空间,或者根据枚举返回某个日志类的命名空间:
Logger& SingletonLoggersManager::GetLoggerForLevel(eLogLevel);
覆盖类的"<<"运算符,以便允许在 Logger 类中输出符合您需求的
https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx
-
定义一个宏以便能够在代码中进行快速调用:
#define LOG(x) SingletonLogger::GetLoggerForLevel(eLogLoevel);
现在,当您在代码中使用时
Log(debug) << "test"
它将扩展到:
(SingletonLogger::GetLoogerForLevel(debug)) << "test";
我在上面看到两个问题。 首先是分叉您的消息(到文件和控制台)。 第二个是用一些额外的东西包装所写的内容。
meta_stream
处理operator<<
重载。 它使用 CRTP 静态调度到其子类型:
template<class D, class substream>
struct meta_stream {
D& self() { return *static_cast<D*>(this); } // cast myself to D
// forwarders of operator<<
template<class X>
friend D& operator<<( meta_stream<D>& d, X const& x ) {
d.self().write_to(x);
return d.self();
}
friend D& operator<<(
meta_stream<D>& d,
substream&(*mod_func)(substream&)
) {
d.self().write_to(mod_func);
return d.self();
}
};
由于 std::endl
和其他修饰符的工作方式,我不得不两次覆盖<<
——它们是重载函数的名称。
这解决了将同一字符串输出到两个不同的 ostream 的问题:
template<class substream>
struct double_ostream:
meta_stream<double_ostream<substream>,substream>
{
substream* a = nullptr;
substream* b = nullptr;
template<class X>
void write_to( X&&x ) {
if (d.a) (*d.a) << x;
if (d.b) (*d.b) << std::forward<X>(x);
}
double_ostream( std::basic_ostream<CharT>* a_, std::basic_ostream<CharT>* b_ ):
a(a_), b(b_)
{}
double_ostream(double_ostream const&)=default;
double_ostream()=default;
double_ostream& operator=(double_ostream const&)=default;
};
请注意通过 meta_stream
使用 CRTP。 我只需要实施write_to
.
首先,将 4 个记录器写入此数组:
enum loglevel {
debug, error, warning, info
};
double_stream<std::ostream> loggers[4];
为每个对象提供一个指向std::cout
的指针和一个指向(存储在其他位置)流的指针,该流包装要将日志保存到的文件。 如果您不希望将该级别记录到该输出流中,则可以传递nullptr
(例如,在发布中,跳过调试日志),并且可以将内容记录到不同的日志文件(调试到一个文件,信息记录到另一个文件)。
double_stream<std::ostream> log( loglevel l ) {
double_stream<std::ostream> retval = loggers[l];
std::string message;
// insert code to generate the current date here in message
// insert code to print out the log level here into message
retval << message;
return retval;
}
现在log(debug) << "hello " << "worldn"
会为你写下你的信息。
如果您不想在日志消息末尾写换行符,您可以做更多花哨的事情,但我怀疑这是否值得。 只需写换行符。
如果您确实想要该功能:
template<class substream>
struct write_after_ostream:
meta_stream<write_after_ostream<substream>,substream>
{
substream* os = nullptr;
template<class X>
void write_to( X&&x ) {
if (os) *os << std::forward<X>(x);
}
~write_after_ostream() {
write_to(message);
}
write_after_ostream( substream* s, std::string m ):
os(s), message(m)
{}
std::string message;
}
write_after_ostream<double_stream<std::ostream>> log( loglevel l ) {
// note & -- store a reference to it, as we will be using a pointer later:
double_stream<std::ostream>& retval = loggers[l];
std::string pre_message;
// insert code to generate the current date here in pre_message
// insert code to print out the log level here into pre_message
retval << pre_message;
return {&retval, "n"};
}
但我认为这不值得。
你可以定义一个enum
,比如
enum loglevel_en {
log_none, log_debug, log_info, log_waring, log_error };
然后有一个全局变量:
enum loglevel_en my_log_level;
并提供一些设置它的方法(例如,从程序参数)。
最后,定义一个宏(在全局标头中)
#define MY_LOG(Lev,Thing) do { if (my_log_level >= Lev)
std::cout << __FILE__ << ":" << __LINE__
<< " " << Thing << std::endl; } while(0)
并像使用它一样使用
MY_LOG(log_info, "x=" << x)
随意改进MY_LOG
宏以输出更多内容(日期等)
您可以改为定义
#define LOG(Lev) if (my_log_level >= Lev) std::cout
但这不适用于这样的代码
if (x>34)
LOG(log_info) << "strange x=" << x;
else return;
所以我强烈建议类似MY_LOG
只有一个像样的解决方案,它并不简单,但它LOG(log_info) << "line 1nline 2" << std::endl;
正确。
您必须实现一个 custòm std::ostreambuf
。它是唯一可以在应用所有常用operator<<
函数后重新格式化输出的类。
特别是,当您有一堆字符要处理时,将调用流缓冲区方法overflow
。您现在可以添加日志级过滤,并可靠地检查格式化字符流中的换行符。
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 在 COUT 语句中使用 COUT 调用函数
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- C++代码停止工作错误使用cout内部函数
- 指针变量在 cout 函数中不起作用
- 如果我想使用 cout 为我的函数提供任何输入......我该如何给出
- 使用<<自有函数的运算符来"override" cout
- std::cout 在打印变量与函数表达式时的行为不同
- 是否可以在每次使用std::cout时执行一个函数
- 不能 std::cout 一个max_element函数
- 打印一个带有静态 int 的函数,有一个 std::cout 和多个 std::cout 有什么区别?
- cout 一个类的函数
- 为什么 cout 语句在传递指向函数的指针时没有执行?
- 将参数传递给成员函数,就像使用 std::cout 一样
- 函数不返回值,但 cout 显示它
- 如何使用 std::cout 或 std::ofstream 作为单个函数的输入?
- Std::cout函数作为参数
- 调试断言在 cout 函数上失败
- 简单(return:void) cout函数返回c++的内存位置
- 如何调用cout函数输出流文件