glog 是一個 C++ 日志庫,它提供 C++ 流式風格的 API。在安裝 glog 之前需要先安裝 gflags,這樣 glog 就可以使用 gflags 去解析命令行參數(可以參見 gflags 安裝教程)。下面是 glog 的安裝步驟:
安裝方式一,下載原始代碼編譯:
$ git clone https://github.com/google/glog.git $ cd glog $ mkdir build $ cmake .. $ make $ sudo make install
安裝之后要怎么使用 glog 呢?如果程序是使用 CMake 構建的,那么只要在 CMakeListsx.txt 里面加上下面幾行配置就可以了:
find_package (glog 0.3.5 REQUIRED) add_executable (main main.cpp) target_link_libraries (main glog::glog)
安裝方式二,直接安裝:
sudo apt-get install libgoogle-glog-dev
若是使用第二種方式安裝的glog,如果程序是使用 CMake 構建的, CMakeListsx.txt 的配置會不同:
首先需要有CMake能找的到的FindGlog.cmake文件,這個文件在Google上可以找的到,見 Glog使用文檔:
Example:
int main(int argc, char* argv[]) { string home = "./log/"; //要先創建此目錄,否則運行報錯. google::InitGoogleLogging(argv[0]); string info_log = home + "master_info_"; google::SetLogDestination(google::INFO, info_log.c_str()); string warning_log = home + "master_warning_"; google::SetLogDestination(google::WARNING, warning_log.c_str()); string error_log = home + "master_error_"; google::SetLogDestination(google::ERROR, error_log.c_str()); string fatal_log = home + "master_fatal_"; google::SetLogDestination(google::FATAL, fatal_log.c_str()); // You can specify one of the following severity levels (in increasing order of severity) LOG(INFO) << "info"; LOG(WARNING) << "warning"; LOG(ERROR) << "error"; LOG(FATAL) << "fatal"; // Logging a FATAL message terminates the program (after the message is logged)! return 0; }
分別會在./log目錄下生成4個log文件。只需要在main函數中初始化一次,便可以在該工程中的其他文件中使用!哪個文件需要寫日志,只需要引用頭文件#include "glog/logging.h"即可