简介
glog 是Google Logging的缩写,是实现了应用级别的日志记录功能的满足C++98标准的库。
安装
安装gflags
# git clone https://github.com/gflags/gflags.git
git clone https://gitcode.net/mirrors/gflags/gflags.git
mkdir build
cd build
cmake -DCMAKE_CXX_FLAGS=-fPIC ..
make
sudo make install
安装gtest
# git clone https://github.com/google/googletest.git
git clone https://gitcode.net/mirrors/google/googletest.git
mkdir build
cd build
cmake ..
make
sudo make install
下载glog源码
git clone https://github.com/google/glog.git
使用cmake 编译
cd glog
cmake -S . -B build -G "Unix Makefiles"
cmake --build build
安装
# 测试编译情况,可省略
cmake --build build --target test
# 安装
cmake --build build --target install
使用
CMakeLists.txt文件修改
cmake_minimum_required (VERSION 3.16)
project (myproj VERSION 1.0)
# find package
find_package (glog 0.6.0 REQUIRED)
add_executable(${PROJECT_NAME}, main.cpp)
# link
target_link_libraries (${PROJECT_NAME} glog::glog)
main.cpp修改
// 包含头文件
#include <glog/logging.h>
// main函数初始化
google::InitGoogleLogging(argv[0]);
使用
标准输出默认只打印ERROR和FATAL级别的信息。默认生成的全部log位于/tmp目录下。
LOG(INFO) << "TESTMESSAGE INFO" << std::endl;
LOG(WARNING) << "TESTMESSAGE WARNING" << std::endl;
LOG(ERROR) << "TESTMESSAGE ERROR" << std::endl;
LOG(FATAL) << "TESTMESSAGE FATAL" << std::endl;
// 默认生成的log位于/tmp目录下
每一行的结尾的 std::endl 可以省略,默认会加换行。
控制台打印
将GLOG_logtostderr设为1,则只会在控制台打印,不会保存在文件。反之设为0,只会保存到文件。
GLOG_logtostderr=1 ./build/mypoj
在程序中设置FLAGS_logtostderr=1也可以打印到控制台。
设置保存的log文件目录
需要在初始化前设置。如果某一级别的路径设为空字符串即""则不会保存该级别的log。
std::string logPath = "./logs/";
std::string logInfoPath = logPath + "info/";
std::string logWarningPath = logPath + "warning/";
std::string logErrorPath = logPath + "error/";
std::string logFatalPath = logPath + "fatal/";
// set before InitGoogleLogging
google::SetLogDestination(google::GLOG_INFO, logInfoPath.c_str());
google::SetLogDestination(google::GLOG_WARNING, logWarningPath.c_str());
google::SetLogDestination(google::GLOG_ERROR, logErrorPath.c_str());
google::SetLogDestination(google::GLOG_FATAL, logFatalPath.c_str());
google::InitGoogleLogging(argv[0]);
INFO级别文件内容格式
Log file created at: yyyy/mm/dd hh:mm:ss
Running on machine: pc
Running duration (h:mm:ss): 0:00:00
Log line format: [IWEF]yyyymmdd hh:mm:ss.uuuuuu threadid file:line] msg
I20230213 11:30:26.891336 2145 main.cpp:65] TESTMESSAGE INFO
W20230213 11:30:26.891638 2145 main.cpp:66] TESTMESSAGE WARNING
E20230213 11:30:26.891757 2145 main.cpp:67] TESTMESSAGE ERROR
F20230213 11:30:26.891894 2145 main.cpp:68] TESTMESSAGE FATAL