在寫代碼的過程中,有些是時候只能用打日誌的方法來看問題。比較常用的日誌庫也很多,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);