linux glog安装使用

glog是Google提供的C++日志库,本文详细介绍了glog的安装步骤,包括依赖库gflags和gtest的安装,以及如何使用cmake进行编译和安装。在使用方面,展示了如何在CMakeLists.txt和源代码中配置glog,以及如何控制日志输出到控制台或文件,并调整日志保存路径和级别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值