对于任何想要简单解决方案的人,我推荐:easylogging++
单头 C++ 日志库。它的重量非常轻,
健壮,快速执行,线程和类型安全,由许多
内置功能。它提供了以您自己的方式编写日志的能力
自定义格式。它还支持记录您的课程,
第三方库、STL、第三方容器等。
这个库有所有内置的东西,以防止使用外部
图书馆。
简单示例:(更多高级示例可在上面的链接中找到)。
#include "easylogging++.h"
INITIALIZE_EASYLOGGINGPP
int main(int argv, char* argc[]) {
LOG(INFO) << "My first info log using default logger";
return 0;
}
类内的示例输出:
2015-08-28 10:38:45,900 调试 [默认] [user@localhost]
[Config::Config(const string)] [src/Config.cpp:7] 读取配置文件:
'config.json'
我尝试了 log4cpp 和 boost::log,但它们不像这个那么容易。
额外内容:最小版本 - LOG 标头
我为基于 easylogging 的更简单的应用程序创建了一个小代码,但不需要初始化(注意它可能不是线程安全的)。代码如下:
/*
* File: Log.h
* Author: Alberto Lepe <dev@alepe.com>
*
* Created on December 1, 2015, 6:00 PM
*/
#ifndef LOG_H
#define LOG_H
#include <iostream>
using namespace std;
enum typelog {
DEBUG,
INFO,
WARN,
ERROR
};
struct structlog {
bool headers = false;
typelog level = WARN;
};
extern structlog LOGCFG;
class LOG {
public:
LOG() {}
LOG(typelog type) {
msglevel = type;
if(LOGCFG.headers) {
operator << ("["+getLabel(type)+"]");
}
}
~LOG() {
if(opened) {
cout << endl;
}
opened = false;
}
template<class T>
LOG &operator<<(const T &msg) {
if(msglevel >= LOGCFG.level) {
cout << msg;
opened = true;
}
return *this;
}
private:
bool opened = false;
typelog msglevel = DEBUG;
inline string getLabel(typelog type) {
string label;
switch(type) {
case DEBUG: label = "DEBUG"; break;
case INFO: label = "INFO "; break;
case WARN: label = "WARN "; break;
case ERROR: label = "ERROR"; break;
}
return label;
}
};
#endif /* LOG_H */
用法:
#include "Log.h"
int main(int argc, char** argv) {
//Config: -----(optional)----
structlog LOGCFG = {};
LOGCFG.headers = false;
LOGCFG.level = DEBUG;
//---------------------------
LOG(INFO) << "Main executed with " << (argc - 1) << " arguments";
}
此代码使用“cout”打印消息,但您可以将其更改为使用“cerr”或附加文件等。我希望它对某人有用。 (注意:我不是 C++ 专家,所以这段代码在极端情况下可能会爆炸)。