在写代码的过程中,有些是时候只能用打日志的方法来看问题。比较常用的日志库也很多,log4cpp,boost.log,pcoc.log,glog。最近用了下glog日志库,比较轻量级,功能也比较齐全。Google总是能带来不少好东西。
官方网址
https://code.google.com/p/google-glog/
官方使用文档
http://google-glog.googlecode.com/svn/trunk/doc/glog.html
解包后会有vs编译的sln文件,这里直接打开可以看到四个项目。代码是一样的,就是编译选项不一样,生成相应的lib。使用的时候需要包含头文件和lib文件。
这里我们希望的是直接包含源代码,编译进自己的工程里。
新建项目,在属性里包含glog头文件目录
使用代码
</pre><p><pre name="code" class="cpp">#include <iostream>
#include <glog/logging.h>
int _tmain(int argc, _TCHAR* argv[])
{
FLAGS_log_dir = "D:\\glog"; //该文件夹一定要存在
FLAGS_max_log_size = 4; //最大日志文件大小 4M
google::InitGoogleLogging("test.exe");
LOG(INFO) << "test";
google::ShutdownGoogleLogging();
return 0;
}
现在就可以直接使用了。
glog 支持功能列表如下:
1, 参数设置,以命令行参数的方式设置标志参数来控制日志记录行为;
2, 严重性分级,根据日志严重性分级记录日志;
3, 可有条件地记录日志信息;
4, 条件中止程序。丰富的条件判定宏,可预设程序终止条件;
5, 异常信号处理。程序异常情况,可自定义异常处理过程;
6, 支持debug功能。可只用于debug模式;
7, 自定义日志信息;
8, 线程安全日志记录方式;
9, 系统级日志记录;
10, google perror风格日志信息;
11, 精简日志字符串信息。
初始化日志模块的一些参数如下(可参见源码src/windows/glog/logging.h line:323-364):
使用什么功能,可以直接在初始化里添加
// Set whether log messages go to stderr instead of logfiles
DECLARE_bool(logtostderr);
// Set whether log messages go to stderr in addition to logfiles.
DECLARE_bool(alsologtostderr);
// Set color messages logged to stderr (if supported by terminal).
DECLARE_bool(colorlogtostderr);
// Log messages at a level >= this flag are automatically sent to
// stderr in addition to log files.
DECLARE_int32(stderrthreshold);
// Set whether the log prefix should be prepended to each line of output.
DECLARE_bool(log_prefix);
// Log messages at a level <= this flag are buffered.
// Log messages at a higher level are flushed immediately.
DECLARE_int32(logbuflevel);
// Sets the maximum number of seconds which logs may be buffered for.
DECLARE_int32(logbufsecs);
// Log suppression level: messages logged at a lower level than this
// are suppressed.
DECLARE_int32(minloglevel);
// If specified, logfiles are written into this directory instead of the
// default logging directory.
DECLARE_string(log_dir);
// Sets the path of the directory into which to put additional links
// to the log files.
DECLARE_string(log_link);
DECLARE_int32(v); // in vlog_is_on.cc
// Sets the maximum log file size (in MB).
DECLARE_int32(max_log_size);
// Sets whether to avoid logging to the disk if the disk is full.
DECLARE_bool(stop_logging_if_full_disk);