📅 2017-Oct-26 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, glog, log ⬩ 📚 Archive
GLog is the logging library from Google for C++. It makes it real easy for you to add logging to any C++ application.
$ sudo apt install libgoogle-glog-dev
Header file: The header file to include in your source file is glog/logging.h
Initialization: You will need to call google::InitGoogleLogging
method with the name of your program as the input parameter to start logging.
Levels: There are 4 levels for logging messages in increasing order of severity: INFO
, WARNING
, ERROR
and FATAL
. These severity levels have values 0, 1, 2 and 3 respectively.
Log function: To log a message, use the LOG
macro, similar to how you use cout
. For example, this example shows logging messages of different severity:
#include <glog/logging.h>
int main(int argc, char* argv[])
{
google::InitGoogleLogging(argv[0]);
LOG(INFO) << "This is an info message";
LOG(WARNING) << "This is a warning message";
LOG(ERROR) << "This is an error message";
LOG(FATAL) << "This is a fatal message";
return 0;
}
Library: To compile a source file using GLog, you will need to link using -lglog
.
Log files: By default, when you run your program, 3 new log files will be created in /tmp
directory. The filenames are of this format:
foobar.home-machine.ashwin.log.ERROR.20171026-220607.21911
foobar.home-machine.ashwin.log.INFO.20171026-220607.21911
foobar.home-machine.ashwin.log.WARNING.20171026-220607.21911
Format:
program_name.hostname.user_name.log.level.date.time.pid
The file with INFO in its name has log messages of levels INFO and above. The file with WARNING int its name has log messages of levels WARNING and above. Similarly, for the file with ERROR in its name.
In addition, 3 symbolic links are created in the same logging directory pointing to the latest log files. These 3 filenames are of the format:
foobar.ERROR
foobar.INFO
foobar.WARNING
Log to display: By default, when you run your program, you will see log messages of ERROR
and FATAL
on the stderr, so they will appear on the console. Note that the first FATAL
message will prompt the killing of your program.
If you want the program to log to stderr instead of writing to log files, set this environment variable GLOG_logtostderr=1
If you want to change the logging directory from /tmp
to some other location, set this environment variable GLOG_log_dir=/some/path
Reference: GLog documentation