Easylogging使用笔记
Easylogging++ 是一个功能强大的 C++ 日志库。以下是使用 Easylogging++ 的基本步骤和一些常用操作:
- 初始化和开启:
首先,在你的主 .cpp 文件中(通常是包含 main() 函数的文件)添加以下代码:
#include "easylogging++.h"
INITIALIZE_EASYLOGGINGPP
这个宏必须在全局范围内使用,且只能使用一次。
- 基本使用:
在需要记录日志的地方,使用以下语法:
LOG(INFO) << "This is an info log";
LOG(WARNING) << "This is a warning";
LOG(ERROR) << "This is an error";
- 配置日志:
你可以通过配置文件或代码来配置 Easylogging++。以下是一个简单的代码配置示例:
el::Configurations conf;
conf.setToDefault();
conf.set(el::Level::Info, el::ConfigurationType::Format, "%datetime %level %msg");
el::Loggers::reconfigureAllLoggers(conf);
- 开启和关闭特定级别的日志:
// 关闭 INFO 级别的日志
el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog);
el::Configurations conf;
conf.set(el::Level::Info, el::ConfigurationType::Enabled, "false");
el::Loggers::reconfigureAllLoggers(conf);// 重新开启 INFO 级别的日志
conf.set(el::Level::Info, el::ConfigurationType::Enabled, "true");
el::Loggers::reconfigureAllLoggers(conf);
- 使用自定义日志器:
el::Logger* customLogger = el::Loggers::getLogger("CustomLogger");
customLogger->info("This is a custom logger message");
- 输出到文件:
conf.set(el::Level::Global, el::ConfigurationType::Filename, "logs/myeasylog.log");
el::Loggers::reconfigureAllLoggers(conf);
- 禁用所有日志:
el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog);
el::Configurations conf;
conf.setToDefault();
conf.set(el::Level::Global, el::ConfigurationType::Enabled, "false");
el::Loggers::reconfigureAllLoggers(conf);
- 重新启用所有日志:
conf.set(el::Level::Global, el::ConfigurationType::Enabled, "true");
el::Loggers::reconfigureAllLoggers(conf);
- 使用性能跟踪:
TIMED_SCOPE(timerBlkObj, "My Timer");
// 你的代码
// 计时器会在作用域结束时自动记录耗时
- 线程安全:
Easylogging++ 默认是线程安全的。如果你不需要线程安全(为了提高性能),可以在编译时定义 ELPP_NO_DEFAULT_LOG_FILE
。
记住,在使用 Easylogging++ 时,你需要在项目中包含 easylogging++.h
和 easylogging++.cc
文件。
这些是 Easylogging++ 的基本用法。该库还提供了许多高级功能,如条件日志、自定义格式化、性能跟踪等。你可以查阅 Easylogging++ 的官方文档以获取更详细的信息和高级用法。