1.拉取
git clone https://github.com/google/glog.git
cd glog
mkdir build
cd build
cmake ..
vs2022打开,编译release的
2. 放到项目中
3.案例一
#include <glog/logging.h>
int main()
{
// 初始化日志系统
google::InitGoogleLogging("MyProgram"); // 初始化glog,并设置程序名
google::SetLogDestination(google::GLOG_INFO, "C:/chenqi/lianxi/glogtest/logs/"); // 设置日志输出路径和级别
google::SetLogFilenameExtension(".log");
// 记录日志
LOG(INFO) << "This is an informational message.";
LOG(WARNING) << "This is a warning message.";
LOG(ERROR) << "This is an error message.";
// 关闭日志系统
google::ShutdownGoogleLogging();
return 0;
}
案例二(google::SetLogSymlink()的使用)
#include <glog/logging.h>
void SomeFunction()
{
// 记录日志
LOG(INFO) << "This is a log message from SomeFunction().";
}
int main()
{
// 初始化日志系统
google::InitGoogleLogging("MyProgram");
google::SetLogDestination(google::GLOG_INFO, "C:/chenqi/lianxi/glogtest/logs/"); // 设置日志输出路径和级别
google::SetLogFilenameExtension(".log");
// 设置符号链接
std::string logDir = "C:/chenqi/lianxi/glogtest/logs/";
std::string symlinkPath = logDir + "latest_log";
google::SetLogSymlink(google::GLOG_INFO, symlinkPath.c_str());
// 记录日志
LOG(INFO) << "This is the main log message.";
// 调用另一个函数
SomeFunction();
// 关闭日志系统
google::ShutdownGoogleLogging();
return 0;
}
在这个示例中,我们创建了一个名为
SomeFunction()
的函数,并在其中记录了一条日志。在main()
函数中,我们使用google::SetLogSymlink()
函数创建了一个符号链接。假设程序运行后生成了多个日志文件,比如
./logs/20230710.log
、./logs/20230711.log
等。当我们运行程序时,符号链接latest_log
会指向最新生成的日志文件,比如./logs/20230711.log
。通过这种方式,我们可以通过访问符号链接
latest_log
来轻松地找到最新的日志文件,而无需知道具体的日志文件名。请确保在运行程序之前先创建一个名为
./logs/
的目录,并确保在程序运行时生成了一些日志文件,以便能够看到符号链接的效果。