google glog 使用方法

程序每次启动都会生成一个日志,为防止常年累月日志过多,本程序设置最多保留5个
只保留最新的5 个log
logprocessor.h

#ifndef LOGPROCESSOR
#define LOGPROCESSOR

#include <stdio.h>

#include "glog/logging.h"
#include "glog/raw_logging.h"

#define OutputLog_Info(format, ...) \
{\
	char szLog[1024 * 5] = { 0 }; \
	sprintf(szLog, format, ##__VA_ARGS__); \
    LOG(INFO) << szLog; \
}

#define OutputLog_Warning(format, ...) \
{\
	char szLog[1024 * 5] = { 0 }; \
	sprintf(szLog, format, ##__VA_ARGS__); \
	LOG(WARNING) << szLog; \
}

#define OutputLog_Error(format, ...) \
{\
	char szLog[1024 * 5] = { 0 }; \
	sprintf(szLog, format, ##__VA_ARGS__); \
	LOG(ERROR) << szLog; \
}
class LogProcessor
{
public:
	LogProcessor();

	~LogProcessor() { google::ShutdownGoogleLogging(); }
};

#endif // LOGPROCESSOR

logprocessor.cpp

#include <stdlib.h>
#include <stdio.h>
#include <chrono>
#include <iostream>

#include <io.h>  
#include <fstream>  
#include <string>
#include <vector>

#include "logprocessor.h"

//配置输出日志的目录:
#define LOGDIR "log"
#define MKDIR "mkdir "LOGDIR

using namespace google;
static int Index = 0;

//将信息输出到单独的文件和 LOG(ERROR)
void SignalHandle(const char* data, int size)
{
	std::string str = std::string(data, size);
	/*
	std::ofstream fs("glog_dump.log",std::ios::app);
	fs<<str;
	fs.close();
	*/
	LOG(ERROR) << str;
	//也可以直接在这里发送邮件或短信通知,不过这个方法是被回调多次的(每次回调只输出一行错误信息,所以如上面的记录到文件,也需要>以追加模式方可),所以这里发邮件或短信不是很适合,不过倒是可以调用一个 SHELL 或 PYTHON 脚本,而此脚本会先 sleep 3秒左右,然后将错
	//误信息通过邮件或短信发送出去,这样就不需要监控脚本定时高频率执行,浪费效率了。
}

long long getCurrentMs()
{
	auto time_now = std::chrono::system_clock::now();
	auto duration_in_ms = std::chrono::duration_cast<std::chrono::milliseconds>(time_now.time_since_epoch());

	return duration_in_ms.count();
}


std::string getCurrentSystemTime()
{
	auto tt = std::chrono::system_clock::to_time_t
		(std::chrono::system_clock::now());
	struct tm* ptm = localtime(&tt);
	char date[60] = { 0 };
	sprintf(date, "%d-%02d-%02d-%02d.%02d.%02d",
		(int)ptm->tm_year + 1900, (int)ptm->tm_mon + 1, (int)ptm->tm_mday,
		(int)ptm->tm_hour, (int)ptm->tm_min, (int)ptm->tm_sec);
	return std::string(date);
}

void GetAllFiles(std::string path, std::vector<std::string>& files)
{

	intptr_t   hFile = 0;
	//文件信息    
	struct _finddata_t fileinfo;//用来存储文件信息的结构体    
	std::string p;
	if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)  //第一次查找  
	{
		do
		{
			if ((fileinfo.attrib &  _A_SUBDIR))  //如果查找到的是文件夹  
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)  //进入文件夹查找  
				{
					files.push_back(p.assign(path).append("\\").append(fileinfo.name));
					GetAllFiles(p.assign(path).append("\\").append(fileinfo.name), files);

				}
			}
			else //如果查找到的不是是文件夹   
			{
				//files.push_back(p.assign(fileinfo.name));  //将文件路径保存,也可以只保存文件名:    p.assign(path).append("\\").append(fileinfo.name)  

				files.push_back(p.assign(path).append("\\").append(fileinfo.name));
			}

		} while (_findnext(hFile, &fileinfo) == 0);

		_findclose(hFile); //结束查找  
	}

}

int com(const void *a, const void *b)
{
	long long * p1, *p2;
	p1 = (long long *)a;  //语句6
	p2 = (long long *)b;  //语句7

	return *p1 > *p2 ? 1 : -1;
}


//GLOG配置:
LogProcessor::LogProcessor()
{
	system(MKDIR);
	google::InitGoogleLogging("CVS");

	google::SetStderrLogging(GLOG_INFO); //设置级别高于 google::INFO 的日志同时输出到屏幕
	FLAGS_colorlogtostderr = true;    //设置输出到屏幕的日志显示相应颜色

	std::vector<std::string> files;

	std::vector<long long> filesNum;
	GetAllFiles(std::string(LOGDIR), files);

	for (int i = 0; i < files.size(); i++)
	{
		int pos0 = files[i].find("LOG_");

		std::string cut = files[i].substr(pos0 + 4, files[i].size());

		char* endptr = NULL;
		long long num = std::strtoll(cut.c_str(), &endptr, 10);

		printf("cut = %s num = %lld \n", cut.c_str(), num);

		filesNum.push_back(num);
		
	}
	qsort(&filesNum.data()[0], filesNum.size(), sizeof(long long), com);
// log 日志只保留5 个
	if (filesNum.size() > 5)
	{
		printf("将要删除的数量 delete num = %d   \n", filesNum.size() - 5);
		long long deleteNum = filesNum.size() - 5;

		for (int i = 0; i < deleteNum; i++)
		{
			std::string logPath = LOGDIR + std::string("/LOG_") + std::to_string(filesNum[i]);
			printf("删除的文件= %s   \n", logPath.c_str());
			remove(logPath.c_str());
		}

	}

	std::string logPath = LOGDIR + std::string("/LOG_") + std::to_string(getCurrentMs());
	//std::string logPath = LOGDIR + std::string("/LOG_") + std::to_string(Index);

	std::cout << logPath;

	google::SetLogDestination(GLOG_INFO, logPath.c_str()); //设置 google::INFO 级别的日志存储路径和文件名前缀
	google::SetLogDestination(GLOG_WARNING, logPath.c_str());   //设置 google::WARNING 级别的日志存储路径和文件名前缀
	google::SetLogDestination(GLOG_ERROR, logPath.c_str());   //设置 google::ERROR 级别的日志存储路径和文件名前缀

	FLAGS_logbufsecs = 0;        //缓冲日志输出,默认为30秒,此处改为立即输出
	FLAGS_max_log_size = 100;  //最大日志大小为 100MB
	FLAGS_stop_logging_if_full_disk = true;     //当磁盘被写满时,停止日志输出
}

main.cpp

#include <stdio.h>
#include "logprocessor.h"

int main()
{
	LogProcessor mLog;
	for (int i = 0; i < 1000; i++)
	{
		OutputLog_Error("hello world .... i = %d \n", i);
	}
	return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值