C++ - single header跨平台高效开源日志库Easylogging++的配置和使用

1 Easylogging++

Easylogging++是一个只有单个头文件的开源跨平台日志库,拥有简单易集成,速度极快,线程安全,高效并可配置可扩展等等优点,现在也是我的主力日志库。

1.1 下载Easylogging++

Github地址:https://github.com/amrayn/easyloggingpp

从Githu下载Easylogging++,下载下来只有两个文件,easylogging++.heasylogging++.cc

1.1 在VS中配置Easylogging++

右键项目-属性-C+±常规-附加包含项目,添加easylogging++.h所在目录

easylogging++.cc添加到项目中。

1.2 使用Easylogging++

(1) 包含头文件

// easylogging++
#include "easylogging++.h"
#define ELPP_THREAD_SAFE

(2) 初始化Easylogging++

INITIALIZE_EASYLOGGINGPP

(3) 设置日志输出配置

static void InitEasyloggingPP()
{
    
    
	el::Configurations conf;

	// 启用日志
	conf.setGlobally(el::ConfigurationType::Enabled, "true");

	//设置日志文件目录以及文件名
	conf.setGlobally(el::ConfigurationType::Filename, "log\\log_%datetime{%Y%M%d %H%m%s}.log");

	//设置日志文件最大文件大小
	conf.setGlobally(el::ConfigurationType::MaxLogFileSize, "20971520");

	//是否写入文件
	conf.setGlobally(el::ConfigurationType::ToFile, "true");

	//是否输出控制台
	conf.setGlobally(el::ConfigurationType::ToStandardOutput, "true");

	//设置日志输出格式
	conf.setGlobally(el::ConfigurationType::Format, "[%datetime] [%loc] [%level] : %msg");

	//设置日志文件写入周期,如下每100条刷新到输出流中
	conf.setGlobally(el::ConfigurationType::LogFlushThreshold, "100");
	
	//设置配置文件
	el::Loggers::reconfigureAllLoggers(conf);
}

(4) 示例程序

// easylogging++
#include "easylogging++.h"
#define ELPP_THREAD_SAFE

INITIALIZE_EASYLOGGINGPP

static void InitEasyloggingPP()
{
    
    
	el::Configurations conf;

	// 启用日志
	conf.setGlobally(el::ConfigurationType::Enabled, "true");

	//设置日志文件目录以及文件名
	conf.setGlobally(el::ConfigurationType::Filename, "log\\log_%datetime{%Y%M%d %H%m%s}.log");

	//设置日志文件最大文件大小
	conf.setGlobally(el::ConfigurationType::MaxLogFileSize, "20971520");

	//是否写入文件
	conf.setGlobally(el::ConfigurationType::ToFile, "true");

	//是否输出控制台
	conf.setGlobally(el::ConfigurationType::ToStandardOutput, "true");

	//设置日志输出格式
	conf.setGlobally(el::ConfigurationType::Format, "[%datetime] [%loc] [%level] : %msg");

	//设置日志文件写入周期,如下每100条刷新到输出流中
	conf.setGlobally(el::ConfigurationType::LogFlushThreshold, "100");
	
	//设置配置文件
	el::Loggers::reconfigureAllLoggers(conf);
}

int main()
{
    
    
	InitEasyloggingPP();

	LOG(INFO) << "Hello World";
}

如果有兴趣,可以访问我的个人站:https://www.stubbornhuang.com/

猜你喜欢

转载自blog.csdn.net/HW140701/article/details/127532430