Skip to content

Instantly share code, notes, and snippets.

@BruceChen7
Last active June 7, 2018 12:12
Show Gist options
  • Save BruceChen7/51d8e590f65b99cef25769095570725a to your computer and use it in GitHub Desktop.
Save BruceChen7/51d8e590f65b99cef25769095570725a to your computer and use it in GitHub Desktop.
[glog的使用] #cpp #glog

常见的使用方式

// http://www.yeolar.com/note/2014/12/20/glog/
#include <glog/logging.h>

int main(int argc, char* argv[]) {
  // Initialize Google's logging library.
  google::InitGoogleLogging(argv[0]);

  // ...
  LOG(INFO) << "Found " << num_cookies << " cookies";
}

日志级别分类

// 可以指定下面这些级别(按严重性递增排序): INFO, WARNING, ERROR, and FATAL 。打印 FATAL 消息会在打印完成后终止程序。和其他日志库类似,级别更高的日志会在同级别和所有低级别的日志文件中打印。

// 设置flags
// 一些flag会影响Glog的输出行为。如果安装了GFlags库,编译时会默认使用它,这样就可以在命令行传递flag(别忘了调用 ParseCommandLineFlags 初始化)。比如你想打开 --logtostderr flag,可以这么用:

// ./your_application --logtostderr=1

// 按条件来打印日志
// 日志只有在满足 num_cookies > 10 时才会打印。
LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";


// 另一种情况,如果代码被执行多次,可能只想对其中某几次打印日志。

// 下面的代码会在执行的第1、11、21、...次时打印日志。 google::COUNTER 用来表示是哪一次执行。

LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";


// 可以将这两种日志用下面的宏合并起来。

LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER
                                        << "th big cookie";

// 不只是每隔几次打印日志,也可以限制在前n次打印日志:
// 上面会在执行的前20次打印日志。
LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie";

// 细节日志
// 当你在追比较复杂的bug的时候,详细的日志信息非常有用。但同时,在通常开发中需要忽略太详细的信息。对这种细节日志的需求,Glog提供了 VLOG 宏,使你可以自定义一些日志级别。通过 --v 可以控制输出的细节日志:

VLOG(1) << "I'm printed when you run the program with --v=1 or higher";
VLOG(2) << "I'm printed when you run the program with --v=2 or higher";

// 和日志级别相反,级别越低的 VLOG 越会打印。比如 --v=1 的话, VLOG(1) 会打印, VLOG(2) 则不会打印。对 VLOG 宏和 --v flag可以指定任何整数,但通常使用较小的正整数。 VLOG 的日志级别是 INFO 。

CHECK宏

DCHECK_GT(time, 19700101000000LL);
DCHECK_LT(time, 21001231235959LL);
CHECK_NOTNULL(handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment