Plog - portable, simple and extensible C++ logging library
Pretty powerful logging library in about 1000 lines of code
- Introduction
- Usage
- Advanced usage
- Architecture
- Miscellaneous notes
- Extending
- Samples
- References
- License
- Version history
Introduction
Hello log!
Plog is a C++ logging library that is designed to be as simple, small and flexible as possible. It is created as an alternative to existing large libraries and provides some unique features as CSV log format and wide string support.
Here is a minimal hello log sample:
#include <plog/Log.h> // Step1: include the headers
#include "plog/Initializers/RollingFileInitializer.h"
int main()
{
plog::init(plog::debug, "Hello.txt"); // Step2: initialize the logger
// Step3: write log messages using a special macro
// There are several log macros, use the macro you liked the most
PLOGD << "Hello log!"; // short macro
PLOG_DEBUG << "Hello log!"; // long macro
PLOG(plog::debug) << "Hello log!"; // function-style macro
// Also you can use LOG_XXX macro but it may clash with other logging libraries
LOGD << "Hello log!"; // short macro
LOG_DEBUG << "Hello log!"; // long macro
LOG(plog::debug) << "Hello log!"; // function-style macro
return 0;
}
And its output:
2015-05-18 23:12:43.921 DEBUG [21428] [main@13] Hello log!
2015-05-18 23:12:43.968 DEBUG [21428] [main@14] Hello log!
2015-05-18 23:12:43.968 DEBUG [21428] [main@15] Hello log!
Features
- Very small (slightly more than 1000 LOC)
- Easy to use
- Headers only
- No 3rd-party dependencies
- Cross-platform: Windows, Linux, FreeBSD, macOS, Android, RTEMS (gcc, clang, msvc, mingw, mingw-w64, icc, c++builder)
- Thread and type safe
- Formatters: TXT, CSV, FuncMessage, MessageOnly
- Appenders: RollingFile, Console, ColorConsole, Android, EventLog, DebugOutput, DynamicAppender
- Automatic 'this' pointer capture (supported only on msvc)
- Lazy stream evaluation
- Unicode aware, files are stored in UTF-8, supports Utf8Everywhere
- Doesn't require C++11
- Extendable
- No
windows.h
dependency - Can use UTC or local time
- Can print buffers in HEX or ASCII
- Can print
std
containers - Uses modern CMake
Usage
To start using plog you need to make 3 simple steps.
Step 1: Adding includes
At first your project needs to know about plog. For that you have to:
- Add
plog/include
to the project include paths - Add
#include <plog/Log.h>
into your cpp/h files (if you have precompiled headers it is a good place to add this include there)
Step 2: Initialization
The next step is to initialize the Logger. This is done by the following plog::init
function:
Logger& init(Severity maxSeverity, const char/wchar_t* fileName, size_t maxFileSize = 0, int maxFiles = 0);
maxSeverity
is the logger severity upper limit. All log messages have its own severity and if it is higher than the limit those messages are dropped. Plog defines the following severity levels:
enum Severity
{
none = 0,
fatal = 1,
error = 2,
warning = 3,
info = 4,
debug = 5,
verbose = 6
};
Note Messages with severity level
none
will always be printed.
The log format is determined automatically by fileName
file extension:
- .csv => CSV format
- anything else => TXT format
The rolling behavior is controlled by maxFileSize
and maxFiles
parameters:
maxFileSize
- the maximum log file size in bytesmaxFiles
- a number of log files to keep
If one of them is zero then log rolling is disabled.
Sample:
plog::init(plog::warning, "c:\\logs\\log.csv", 1000000, 5);
Here the logger is initialized to write all messages with up to warning severity to a file in csv format. Maximum log file size is set to 1'000'000 bytes and 5 log files are kept.
Note See Custom initialization for advanced usage.
Step 3: Logging
Logging is performed with the help of special macros. A log message is constructed using stream output operators <<
. Thus it is type-safe and extendable in contrast to a format string output.
Basic logging macros
This is the most used type of logging macros. They do unconditional logging.
Long macros:
PLOG_VERBOSE << "verbose";
PLOG_DEBUG << "debug";
PLOG_INFO << "info";
PLOG_WARNING << "warning";
PLOG_ERROR << "error";
PLOG_FATAL << "fatal";
PLOG_NONE << "none";
Short macros:
PLOGV << "verbose";
PLOGD << "debug";
PLOGI << "info";
PLOGW << "warning";
PLOGE << "error";
PLOGF << "fatal";
PLOGN << "none";
Function-style macros:
PLOG(severity) << "msg";
Conditional logging macros
These macros are used to do conditional logging. They accept a condition as a parameter and perform logging if the condition is true.
Long macros:
PLOG_VERBOSE_IF(cond) << "verbose";
PLOG_DEBUG_IF(cond) << "debug";
PLOG_INFO_IF(cond) << "info";
PLOG_WARNING_IF(cond) << "warning";
PLOG_ERROR_IF(cond) << "error";
PLOG_FATAL_IF(cond) << "fatal";
PLOG_NONE_IF(cond) << "none";
Short macros:
PLOGV_IF(cond) << "verbose";
PLOGD_IF(cond) << "debug";
PLOGI_IF(cond) << "info";
PLOGW_IF(cond) << "warning";
PLOGE_IF(cond) << "error";
PLOGF_IF(cond) << "fatal";
PLOGN_IF(cond) << "none";
Function-style macros:
PLOG_IF(severity, cond) << "msg";
Logger severity checker
In some cases there is a need to perform a group of actions depending on the current logger severity level. There is a special macro for that. It helps to minimize performance penalty when the logger is inactive.
IF_PLOG(severity)
Sample:
IF_PLOG(plog::debug) // we want to execute the following statements only at debug severity (and higher)
{
for (int i = 0; i < vec.size(); ++i)
{
PLOGD << "vec[" << i << "]: " << vec[i];
}
}
Advanced usage
Changing severity at runtime
It is possible to set the maximum severity not only at the logger initialization time but at any time later. There are special accessor methods:
Severity Logger::getMaxSeverity() const;
Logger::setMaxSeverity(Severity severity);
To get the logger use plog::get
function:
Logger* get();
Sample:
plog::get()->setMaxSeverity(plog::debug);
Custom initialization
Non-typical log cases require the use of custom initialization. It is done by the following plog::init
function:
Logger& init(Severity maxSeverity = none, IAppender* appender = NULL);
You have to construct an Appender parameterized with a Formatter and pass it to the plog::init
function.
Note The appender lifetime should be static!
Sample:
static plog::ConsoleAppender<plog::TxtFormatter> consoleAppender;
plog::init(plog::debug, &consoleAppender);
Multiple appenders
It is possible to have multiple Appenders within a single Logger. In such case log message will be written to all of them. Use the following method to accomplish that:
Logger& Logger::addAppender(IAppender* appender);
Sample:
static plog::RollingFileAppender<plog::CsvFormatter> fileAppender("MultiAppender.csv", 8000, 3); // Create the 1st appender.
static plog::ConsoleAppender<plog::TxtFormatter> consoleAppender; // Create the 2nd appender.
plog::init(plog::debug, &fileAppender).addAppender(&consoleAppender); // Initialize the logger with the both appenders.
Here the logger is initialized in the way when log messages are written to both a file and a console.
Refer to MultiAppender for a complete sample.
Multiple loggers
Multiple Loggers can be used simultaneously each with their own separate configuration. The Loggers differ by their instanceId (that is implemented as a template parameter). The default instanceId is zero. Initialization is done by the appropriate template plog::init
functions:
Logger<instanceId>& init<instanceId>(...);
To get a logger use plog::get
function (returns NULL
if the logger is not initialized):
Logger<instanceId>* get<instanceId>();
All logging macros have their special versions that accept an instanceId parameter. These kind of macros have an underscore at the end:
PLOGD_(instanceId) << "debug";
PLOGD_IF_(instanceId, condition) << "conditional debug";
IF_PLOG_(instanceId, severity)
Sample:
enum // Define log instanceIds. Default is 0 and is omitted from this enum.
{
SecondLog = 1
};
int main()
{
plog::init(plog::debug, "MultiInstance-default.txt"); // Initialize the default logger instance.
plog::init<SecondLog>(plog::debug, "MultiInstance-second.txt"); // Initialize the 2nd logger instance.
// Write some messages to the default log.
PLOGD << "Hello default log!";
// Write some messages to the 2nd log.
PLOGD_(SecondLog) << "Hello second log!";
return 0;
}
Refer to MultiInstance for a complete sample.
Share log instances across modules (exe, dll, so, dylib)
For applications that consist of several binary modules, plog instances can be local (each module has its own instance) or shared (all modules use the same instance). In case of shared you have to initialize plog only in one module, other modules will reuse that instance.
Sharing behavior is controlled by the following macros and is OS-dependent:
Macro | OS | Behavior |
---|---|---|
PLOG_GLOBAL | Linux/Unix | Shared |
PLOG_LOCAL | Linux/Unix | Local |
PLOG_EXPORT | Linux/Unix | n/a |
PLOG_IMPORT | Linux/Unix | n/a |
Linux/Unix | According to compiler settings | |
PLOG_GLOBAL | Windows | n/a |
PLOG_LOCAL | Windows | Local |
PLOG_EXPORT | Windows | Shared (exports) |
PLOG_IMPORT | Windows | Shared (imports) |
Windows | Local |
For sharing on Windows one module should use PLOG_EXPORT
and others should use PLOG_IMPORT
. Also be careful on Linux/Unix: if you don't specify sharing behavior it will be determined by compiler settings (-fvisibility
).
Refer to Shared for a complete sample.
Chained loggers
A Logger can work as an Appender for another Logger. So you can chain several loggers together. This is useful for streaming log messages from a shared library to the main application binary.
Important: don't forget to specify PLOG_LOCAL
sharing mode on Linux/Unix systems for this sample.
Sample:
// shared library
// Function that initializes the logger in the shared library.
extern "C" void EXPORT initialize(plog::Severity severity, plog::IAppender* appender)
{
plog::init(severity, appender); // Initialize the shared library logger.
}
// Function that produces a log message.
extern "C" void EXPORT foo()
{
PLOGI << "Hello from shared lib!";
}
// main app
// Functions imported from the shared library.
extern "C" void initialize(plog::Severity severity, plog::IAppender* appender);
extern "C" void foo();
int main()
{
plog::init(plog::debug, "ChainedApp.txt"); // Initialize the main logger.
PLOGD << "Hello from app!"; // Write a log message.
initialize(plog::debug, plog::get()); // Initialize the logger in the shared library. Note