Logging for C++: Best Solutions
Logging is a critically important aspect of developing any serious application in C++. A properly configured logging system allows you to track the program's state, identify errors, conduct audits, and debug in a production environment. Unlike simple std::cout, professional libraries provide severity levels (trace, debug, info, warn, error, fatal), file rotation, asynchronous writing, and minimal performance impact. In this article, we will look at three best solutions for C++: spdlog, Google glog, and P7.
1. spdlog — Fast and Modern Logger
spdlog is a header-only library written in C++11/14/17. It is considered one of the fastest loggers in the C++ ecosystem. Key advantages: support for asynchronous mode, many output formats (console, file, syslog, custom), colored console output, and minimal memory consumption.
Basic usage example:
#include "spdlog/spdlog.h"#include "spdlog/sinks/basic_file_sink.h"
int main() { // Create a file logger auto file_logger = spdlog::basic_logger_mt("file_logger", "logs/app.log"); // Set the logging level spdlog::set_level(spdlog::level::debug);
// Log messages spdlog::info("Application started"); file_logger->warn("User {} attempted to log in with an incorrect password", "admin"); file_logger->error("Database connection error: {}", 404);
// Asynchronous logging spdlog::flush_every(std::chrono::seconds(3)); return 0;}Key features:
- Performance: up to 5-10 million messages per second in asynchronous mode.
- Flexibility: support for sinks (outputs) — console, file, syslog, Telegram, Kafka.
- File rotation: automatic log creation by size or time.
- Colored output: levels are colored for quick visual diagnostics.
2. Google glog — A Time-Tested Logger
Google glog (glog) is a library from Google, developed for the company's internal needs. It is simple, reliable, and well-suited for server applications. The main focus is on log categorization and automatic writing to files.
Usage example:
#include <glog/logging.h>
int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]);
// Configure output to file FLAGS_log_dir = "./logs"; FLAGS_stderrthreshold = 1; // Output WARNING and above to stderr
LOG(INFO) << "Server started on port " << 8080; LOG(WARNING) << "Low memory: " << 512 << " MB"; LOG(ERROR) << "Failed to open configuration file";
// Conditional logging int x = 5; LOG_IF(INFO, x > 3) << "x is greater than 3";
google::ShutdownGoogleLogging(); return 0;}Features of glog:
- Automatic rotation: files are created by day and size.
- Conditional logging:
LOG_IF,CHECKfor assertions. - Signal support: automatically logs a stack dump on crash.
- Minimal configuration: works "out of the box".
3. P7 — Logger for High-Load Systems
P7 (or P7::Logger) is a library focused on maximum performance and minimal impact on application latency. It uses an asynchronous queue and minimizes locks. It is ideal for game engines, financial systems, and