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

一、Easylogging++简介

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

二、下载Easylogging++

Github地址:https://github.com/cuttingdust/easyloggingpp.git

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

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

在这里插入图片描述
在这里插入图片描述

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

三、使用Easylogging++

(一) 包含头文件

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

(二) 初始化Easylogging++

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);
}

(四) 示例程序

// 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";
}
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐