What it is
glog is Google’s C++ logging library that provides application-level logging with different severity levels (INFO, WARNING, ERROR, FATAL). It is designed for robustness, simplicity, and performance, making it suitable for large-scale systems.
glog provides macros for logging at different severity levels. It also supports logging to files, conditional logging, and custom log sinks.
Installation
find_package(glog CONFIG REQUIRED)Getting started
The smallest useful thing you can do with it, and what each part means.
#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 fatal and will terminate.";
return 0;
}Advanced usage
Where the library earns its place over a simpler alternative.
int x = 5;
LOG_IF(INFO, x > 0) << "x is positive";FLAGS_v = 2;
VLOG(1) << "Verbose logging at level 1";
VLOG(2) << "Verbose logging at level 2";int* ptr = nullptr;
CHECK_NOTNULL(ptr);class MyLogSink : public google::LogSink {
void send(google::LogSeverity severity, const char* full_filename,
const char* base_filename, int line, const struct ::tm* tm_time,
const char* message, size_t message_len) override {
std::cout << "Custom log: " << message << std::endl;
}
};
MyLogSink sink;
google::AddLogSink(&sink);Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- Logs not appearing
- Ensure `InitGoogleLogging` is called and check that log files are accessible.
- Fatal errors terminate unexpectedly
- Use `LOG(ERROR)` instead of `LOG(FATAL)` unless termination is required.
- Performance overhead in production
- Use lower verbosity levels and disable unnecessary logs with runtime flags.
Best practices
- Initialize glog early in the main function using `InitGoogleLogging`.
- Use severity levels consistently to separate normal logs from warnings and errors.
- Avoid `LOG(FATAL)` except for unrecoverable errors; it terminates the application.
- Use `CHECK` macros to enforce invariants in critical code paths.
- Combine glog with monitoring tools by redirecting log sinks if necessary.
Background
Why it exists, and what it was reacting to.
glog was developed at Google to provide developers with a powerful yet simple logging solution for C++ projects. Unlike syslog or printf-based approaches, glog adds structured logging with severity levels, stack traces on fatal errors, and flexible runtime configuration. It has since been open-sourced and is widely used across many C++ projects.
