工作日常需要,调试和打印日志,方便人们查看出错信息。
在网上搜索到了spdlog
下面给出简单的使用例子。
spdlog库下载地址GitHub
大家可用码云仓库下载,比较快一点
下载解压后:
在vs项目包含include路径即可使用。
下面给简单的打开文件输入日志实例。其他具体功能可看GitHub文档。
#include <iostream>
#include <string>
#include "spdlog/spdlog.h"
using namespace std;
//声明命名空间
using namespace spdlog;
//自己定义的日志名和保存文件地址
auto my_logger = spdlog::basic_logger_mt("lala", "./123.log");
int main()
{
string jj = "33";
string aa = "44";
my_logger->info("haha{0}{1}",jj,aa);
//保存缓冲数据。防止程序关闭,未保存日志信息
my_logger->flush();
return 0;
}
运行后,就会生成一个日志信息。
日志按日期文件夹生成和滚动日志:
先按日期新建文件夹,再依据上级路径生成满出空间则新建的日志。
//所需头文件
#include <direct.h>
#include <io.h>
#include <time.h>
#include <sys/timeb.h>
#include <iostream>
using namespace std;
using namespace spdlog;
//获取时间日期
string gettime()
{
//获取毫秒级时间操作
SYSTEMTIME sys;
GetLocalTime(&sys);
char shijianchuo[50];
sprintf_s(shijianchuo, "%04d-%02d-%02d"
, sys.wYear, sys.wMonth, sys.wDay
);
string t_date=shijianchuo;
return t_time;
}
//创建日志文件夹
void createrz()
{
//建立日志文件夹
std::string logprefix = "./log";
if (_access(logprefix.c_str(), 0) == -1) //如果文件夹不存在
{
cout << "not file log ,mkdir log " << endl;
_mkdir(logprefix.c_str());
}
else
{
cout << " has been exist log file" << endl;
}
//建立日志文件
std::string rizhiprefix = "./log/" + gettime();
if (_access(rizhiprefix.c_str(), 0) == -1) //如果文件夹不存在
{
cout << "not file datefile ,mkdir datefile " << endl;
_mkdir(rizhiprefix.c_str());
}
else
{
cout << " has been exist datefile" << endl;
}
}
//滚动1m空间大小+新建2次(就是超出内容的话是3个文件)
auto my_logger = spdlog::rotating_logger_mt("lala", rizhiprefix + "/lala.log", 1048576 * 1, 3);//定义日志地址
int main()
{
createrz();
return 0;
}
还有一个:当你把程序挂1天以上,想要重复使用日志变量,
需要先释放掉,重新赋值后即可修改日志生成的路径。
在重新赋值前添加以下语句:
spdlog::drop_all();
详细解释,我也不是特别清楚,有熟悉spdlog日志库的朋友,可从评论留言告诉我,大家一起学习一下。
参考文章:
https://blog.csdn.net/zhaotun123/article/details/99672298
https://www.cnblogs.com/oucsheep/p/8426548.html
https://blog.csdn.net/haojie_superstar/article/details/89383433