日志库在项目开发中经常用到,其中glog是c++比较常用的日志库,本篇介绍glog在window平台的编译。
1.下载glog源码
https://github.com/google/glog
2.下载安装cmake
3.解压glog源码,在E:\glog-master目录下创建output目录, 打开cmake-gui,设置源码目录和编译输出目录
点击【Configure】按钮, 配置相关参数
生成编译文件
点击【Generate】按钮生成VS的解决文案文件
点击【Open Project】按钮,打开VS工程
编译所有项目,生成动态库和exe
生成的文件在E:\glog-master\output\Debug目录下
把动态库glogd.dll和头文件(E:\glog-master\output\glog)放到项目的相应目录,编写测试代码
#include "glog/logging.h"
void initLog(const char* argv0, const QString &exePath)
{
//设置日志文件路径
QString logPath = exePath + "/logs" ;
QDir logPathDir(logPath);
if(!logPathDir.exists()){
QDir().mkpath(logPathDir.absolutePath());
}
logPath = logPath + "/INFO_";
std::string glogFile = logPath.toStdString();
google::SetLogDestination(google::GLOG_INFO, glogFile.c_str());
google::InitGoogleLogging(argv0);
google::SetLogFilenameExtension(".log");
LOG(INFO) << "Hello,GLOG!";
LOG(INFO) << "info";
LOG(WARNING) << "warning";
//LOG(ERROR) << "error";
LOG(INFO) << "info2";
}
int main(int argc, char* argv[]) {
QString exePath = QCoreApplication::applicationDirPath();
initLog(argv[0], exePath);
google::ShutdownGoogleLogging();
return 0;
}
这样生成的日志文件都是以日期时间+程序pid命名的,每次程序启动都会创建一个新日志文件,
如果想要生成固定的文件名,修改源码
void LogFileObject::Write(bool force_flush, time_t timestamp, const char* message, size_t message_len)函数
time_pid_stream << 1900+tm_time.tm_year
<< setw(2) << 1+tm_time.tm_mon
<< setw(2) << tm_time.tm_mday
<< '-'
<< setw(2) << tm_time.tm_hour
<< setw(2) << tm_time.tm_min
<< setw(2) << tm_time.tm_sec
<< '.'
<< GetMainThreadPid();
改成
time_pid_stream << 1900+tm_time.tm_year
<< setw(2) << 1+tm_time.tm_mon
<< setw(2) << tm_time.tm_mday;
这样就是以天的文件名了,生成的日志会追加到当天的日志文件中。