google glog 简单使用小结

glog 是 google 的一个 c++ 开源日志系统,轻巧灵活,入门简单,而且功能也比较完善。

安装
以下是官方的安装方法,一句命令:

➜  git clone https://github.com/google/glog.git
➜  cd glog 
➜  ./autogen.sh && ./configure && make && make install


使用

从一个最简单的程序开始:

#include <glog/logging.h>

int main(int argc,char* argv[])
{
    google::InitGoogleLogging(argv[0]); //初始化 glog
    LOG(INFO) << "Hello,GOOGLE!";
}

编译:

➜ g++ glog_test2.cpp -lglog -lgflags -lpthread -o glog_test #编译
➜ ./glog_test

➜ ll /tmp  # 默认日志在 /tmp 下
total 28K
-rw-rw-r-- 1 angryrookie angryrookie  193  7月  3 22:04 glog_test.cheng.angryrookie.log.INFO.20160703-220405.6569
lrwxrwxrwx 1 angryrookie angryrookie   57  7月  3 22:04 glog_test.INFO -> glog_test.cheng.angryrookie.log.INFO.20160703-220405.6569
➜ cat /tmp/glog_test.INFO 
Log file created at: 2016/07/03 22:04:05
Running on machine: cheng
Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg
I0703 22:04:05.242153  6569 glog_test2.cpp:7] Hello,GLOG!

这里没有指定日志文件的目录,默认会放在 /tmp 下,文件名的格式为 <program name>.<hostname>.<user name>.log.<severity level>.<date>.<time>.<pid>。我们再看一下代码打印出的日志信息:

I0703 22:04:05.242153  6569 glog_test2.cpp:7] Hello,GLOG!
这一行信息对应的分别是:I+日期 时:分:秒.微秒 线程号 源文件名:行数] 信息,这些信息对定位问题,做统计都很有效,可以根据具体项目来做分析。

修改日志文件的位置

glog 的日志会根据日志严重性分级记录日志,标准的分级为:INFO, WARNING, ERROR, FATAL。不同级别的日志信息会输出到不同文件,同时高级别的日志也会写入到低级别中。

再看个例子:

#include <glog/logging.h>
#include <gflags/gflags.h>
#include <iostream>
#include <cstdlib>

int main(int argc, char** argv) 
{
    google::InitGoogleLogging(argv[0]);
    // create logpath
    std::string str_des;
    str_des.append("mkdir -p ");
    str_des.append("log");
    system(str_des.c_str());
    // INFO
    std::string str_info;
    str_info.append("./log");
    str_info.append("/INFO_");
    google::SetLogDestination(google::INFO, str_info.c_str());
    // WARNING
    std::string str_warn;
    str_warn.append("./log");
    str_warn.append("/WARNING_");
    google::SetLogDestination(google::WARNING, str_warn.c_str());
    LOG(WARNING) << "The is a warning!";
    // my own type
    std::string str_pro;
    str_pro.append("./log");
    str_pro.append("/PROFILE_");
    google::SetLogDestination(google::WARNING, str_pro.c_str());
    LOG(WARNING) << "The is my own type!";
    // stop glog
    google::ShutdownGoogleLogging();
}

再次编译运行:

➜ g++ glog_test2.cpp -lglog -lgflags -lpthread -o glog_test

会在当前文件夹下生成log文件夹并存放日志信息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值