C++打印日誌spdlog庫

工作日常需要,調試和打印日誌,方便人們查看出錯信息。
在網上搜索到了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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章