How to install and use GLog

GLog is the logging library from Google for C++. It makes it real easy for you to add logging to any C++ application.

  • Install: Installing GLog header files and library files is easy:
$ 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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s