...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
#include <boost/log/sources/basic_logger.hpp
>
The simplest logging sources provided by the library are loggers logger
and its thread-safe
version, logger_mt
(wlogger
and
wlogger_mt
for wide-character logging, accordingly). These loggers only provide the
ability to store source-specific attributes within themselves and, of course,
to form log records. This type of logger should probably be used when there
is no need for advanced features like severity level checks. It may well
be used as a tool to collect application statistics and register application
events, such as notifications and alarms. In such cases the logger is normally
used in conjunction with scoped
attributes to attach the needed data to the notification event.
Below is an example of usage:
class network_connection { src::logger m_logger; logging::attribute_set::iterator m_remote_addr; public: void on_connected(std::string const& remote_addr) { // Put the remote address into the logger to automatically attach it // to every log record written through the logger m_remote_addr = m_logger.add_attribute("RemoteAddress", attrs::constant< std::string >(remote_addr)).first; // The straightforward way of logging if (logging::record rec = m_logger.open_record()) { rec.attribute_values().insert("Message", attrs::make_attribute_value(std::string("Connection established"))); m_logger.push_record(boost::move(rec)); } } void on_disconnected() { // The simpler way of logging: the above "if" condition is wrapped into a neat macro BOOST_LOG(m_logger) << "Connection shut down"; // Remove the attribute with the remote address m_logger.remove_attribute(m_remote_addr); } void on_data_received(std::size_t size) { // Put the size as an additional attribute // so it can be collected and accumulated later if needed. // The attribute will be attached only to this log record. BOOST_LOG(m_logger) << logging::add_value("ReceivedSize", size) << "Some data received"; } void on_data_sent(std::size_t size) { BOOST_LOG(m_logger) << logging::add_value("SentSize", size) << "Some data sent"; } };
The class network_connection
in the code snippet above represents an approach to implementing simple
logging and statistical information gathering in a network-related application.
Each of the presented methods of the class effectively marks a corresponding
event that can be tracked and collected on the sinks level. Furthermore,
other methods of the class, that are not shown here for simplicity, are
able to write logs too. Note that every log record ever made in the connected
state of the network_connection
object will be implicitly marked up with the address of the remote site.
#include <boost/log/sources/severity_feature.hpp
> #include <boost/log/sources/severity_logger.hpp
>
The ability to distinguish some log records from others based on some kind
of level of severity or importance is one of the most frequently requested
features. The class templates severity_logger
and severity_logger_mt
(along with their wseverity_logger
and wseverity_logger_mt
wide-character counterparts) provide this functionality.
The loggers automatically register a special source-specific attribute
"Severity", which can be set for every record in a compact and
efficient manner, with a named argument severity
that can be passed to the constructor and/or the open_record
method. If passed to the logger constructor, the severity
argument sets the default value of the severity level that will be used
if none is provided in the open_record
arguments. The severity
argument passed to the open_record
method sets the level of the particular log record being made. The type
of the severity level can be provided as a template argument for the logger
class template. The default type is int
.
The actual values of this attribute and their meaning are entirely user-defined.
However, it is recommended to use the level of value equivalent to zero
as a base point for other values. This is because the default-constructed
logger object sets its default severity level to zero. It is also recommended
to define the same levels of severity for the entire application in order
to avoid confusion in the written logs later. The following code snippet
shows the usage of severity_logger
.
// We define our own severity levels enum severity_level { normal, notification, warning, error, critical }; void logging_function() { // The logger implicitly adds a source-specific attribute 'Severity' // of type 'severity_level' on construction src::severity_logger< severity_level > slg; BOOST_LOG_SEV(slg, normal) << "A regular message"; BOOST_LOG_SEV(slg, warning) << "Something bad is going on but I can handle it"; BOOST_LOG_SEV(slg, critical) << "Everything crumbles, shoot me now!"; }
void default_severity() { // The default severity can be specified in constructor. src::severity_logger< severity_level > error_lg(keywords::severity = error); BOOST_LOG(error_lg) << "An error level log record (by default)"; // The explicitly specified level overrides the default BOOST_LOG_SEV(error_lg, warning) << "A warning level log record (overrode the default)"; }
Or, if you prefer logging without macros:
void manual_logging() { src::severity_logger< severity_level > slg; logging::record rec = slg.open_record(keywords::severity = normal); if (rec) { logging::record_ostream strm(rec); strm << "A regular message"; strm.flush(); slg.push_record(boost::move(rec)); } }
And, of course, severity loggers also provide the same functionality the basic loggers do.
#include <boost/log/sources/channel_feature.hpp
> #include <boost/log/sources/channel_logger.hpp
>
Sometimes it is important to associate log records with some application
component, such as the module or class name, the relation of the logged
information to some specific domain of application functionality (e.g.
network or file system related messages) or some arbitrary tag that can
be used later to route these records to a specific sink. This feature is
fulfilled with loggers channel_logger
,
channel_logger_mt
and their wide-char counterparts wchannel_logger
,
wchannel_logger_mt
.
These loggers automatically register an attribute named "Channel".
The default channel name can be set in the logger constructor with a named
argument channel
. The type
of the channel attribute value can be specified as a template argument
for the logger, with std::string
(std::wstring
in case of wide character loggers)
as a default. Aside from that, the usage is similar to the basic
loggers:
class network_connection { src::channel_logger< > m_net, m_stat; logging::attribute_set::iterator m_net_remote_addr, m_stat_remote_addr; public: network_connection() : // We can dump network-related messages through this logger // and be able to filter them later m_net(keywords::channel = "net"), // We also can separate statistic records in a different channel // in order to route them to a different sink m_stat(keywords::channel = "stat") { } void on_connected(std::string const& remote_addr) { // Add the remote address to both channels attrs::constant< std::string > addr(remote_addr); m_net_remote_addr = m_net.add_attribute("RemoteAddress", addr).first; m_stat_remote_addr = m_stat.add_attribute("RemoteAddress", addr).first; // Put message to the "net" channel BOOST_LOG(m_net) << "Connection established"; } void on_disconnected() { // Put message to the "net" channel BOOST_LOG(m_net) << "Connection shut down"; // Remove the attribute with the remote address m_net.remove_attribute(m_net_remote_addr); m_stat.remove_attribute(m_stat_remote_addr); } void on_data_received(std::size_t size) { BOOST_LOG(m_stat) << logging::add_value("ReceivedSize", size) << "Some data received"; } void on_data_sent(std::size_t size) { BOOST_LOG(m_stat) << logging::add_value("SentSize", size) << "Some data sent"; } };
It is also possible to set the channel name of individual log records.
This can be useful when a global
logger is used instead of an object-specific one. The channel name
can be set by calling the channel
modifier on the logger or by using a special macro for logging. For example:
// Define a global logger BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(my_logger, src::channel_logger_mt< >, (keywords::channel = "general")) class network_connection { std::string m_remote_addr; public: void on_connected(std::string const& remote_addr) { m_remote_addr = remote_addr; // Put message to the "net" channel BOOST_LOG_CHANNEL(my_logger::get(), "net") << logging::add_value("RemoteAddress", m_remote_addr) << "Connection established"; } void on_disconnected() { // Put message to the "net" channel BOOST_LOG_CHANNEL(my_logger::get(), "net") << logging::add_value("RemoteAddress", m_remote_addr) << "Connection shut down"; m_remote_addr.clear(); } void on_data_received(std::size_t size) { BOOST_LOG_CHANNEL(my_logger::get(), "stat") << logging::add_value("RemoteAddress", m_remote_addr) << logging::add_value("ReceivedSize", size) << "Some data received"; } void on_data_sent(std::size_t size) { BOOST_LOG_CHANNEL(my_logger::get(), "stat") << logging::add_value("RemoteAddress", m_remote_addr) << logging::add_value("SentSize", size) << "Some data sent"; } };
Note that changing the channel name is persistent, so unless the channel name is reset, the subsequent records will also belong to the new channel.
Tip | |
---|---|
For performance reasons it is advised to avoid dynamically setting the channel name individually for every log record, when possible. Changing the channel name involves dynamic memory allocation. Using distinct loggers for different channels allows to avoid this overhead. |
#include <boost/log/sources/exception_handler_feature.hpp
>
The library provides a logger feature that enables the user to handle and/or
suppress exceptions at the logger level. The exception_handler
feature adds a set_exception_handler
method to the logger that allows setting a function object to be called
if an exception is thrown from the logging core during the filtering or
processing of log records. One can use the library-provided
adapters to simplify implementing exception handlers. Usage example
is as follows:
enum severity_level { normal, warning, error }; // A logger class that allows to intercept exceptions and supports severity level class my_logger_mt : public src::basic_composite_logger< char, my_logger_mt, src::multi_thread_model< boost::shared_mutex >, src::features< src::severity< severity_level >, src::exception_handler > > { BOOST_LOG_FORWARD_LOGGER_MEMBERS(my_logger_mt) }; BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_logger, my_logger_mt) { my_logger_mt lg; // Set up exception handler: all exceptions that occur while // logging through this logger, will be suppressed lg.set_exception_handler(logging::make_exception_suppressor()); return lg; } void logging_function() { // This will not throw BOOST_LOG_SEV(my_logger::get(), normal) << "Hello, world"; }
Tip | |
---|---|
Logging core and sink frontends also support installing exception handlers. |
#include <boost/log/sources/severity_channel_logger.hpp
>
If you wonder whether you can use a mixed set of several logger features
in one logger, then yes, you certainly can. The library provides severity_channel_logger
and severity_channel_logger_mt
(with their wide-char analogues wseverity_channel_logger
and wseverity_channel_logger_mt
)
which combine features of the described loggers with severity
level and channels
support. The composite loggers are templates, too, which allows you to
specify severity level and channel types. You can also design your own
logger features and combine them with the ones provided by the library,
as described in the Extending the
library section.
The usage of the loggers with several features does not conceptually differ
from the usage of the single-featured loggers. For instance, here is how
a severity_channel_logger_mt
could be used:
enum severity_level { normal, notification, warning, error, critical }; typedef src::severity_channel_logger_mt< severity_level, // the type of the severity level std::string // the type of the channel name > my_logger_mt; BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_logger, my_logger_mt) { // Specify the channel name on construction, similarly as with the channel_logger return my_logger_mt(keywords::channel = "my_logger"); } void logging_function() { // Do logging with the severity level. The record will have both // the severity level and the channel name attached. BOOST_LOG_SEV(my_logger::get(), normal) << "Hello, world!"; }
#include <boost/log/sources/global_logger_storage.hpp
>
Sometimes it is inconvenient to have a logger object to be able to write
logs. This issue is often present in functional-style code with no obvious
places where a logger could be stored. Another domain where the problem
persists is generic libraries that would benefit from logging. In such
cases it would be more convenient to have one or several global loggers
in order to easily access them in every place when needed. In this regard
std::cout
is a good example of such a logger.
The library provides a way to declare global loggers that can be accessed
pretty much like std::cout
. In fact, this feature can be used
with any logger, including user-defined ones. Having declared a global
logger, one can be sure to have a thread-safe access to this logger instance
from any place of the application code. The library also guarantees that
a global logger instance will be unique even across module boundaries.
This allows employing logging even in header-only components that may get
compiled into different modules.
One may wonder why there is a need for something special in order to create global loggers. Why not just declare a logger variable at namespace scope and use it wherever you need? While technically this is possible, declaring and using global logger variables is complicated for the following reasons:
main
).
a
has external linkage and was compiled into modules X and Y, each of
these modules has its own copy of variable a
.
To make things worse, on other platforms this variable can be shared
between the modules.
Global logger storage is intended to eliminate all these problems.
The easiest way to declare a global logger is to use the following macro:
BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT
(my_logger, src::severity_logger_mt< >)
The my_logger
argument
gives the logger a name that may be used to acquire the logger instance.
This name acts as a tag of the declared logger. The second parameter denotes
the logger type. In multithreaded applications, when the logger can be
accessed from different threads, users will normally want to use the thread-safe
versions of loggers.
If passing arguments to the logger constructor is needed, there is another macro:
BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS
(
my_logger,
src::severity_channel_logger< >,
(keywords::severity = error)(keywords::channel = "my_channel"))
The last macro argument is a Boost.Preprocessor sequence of arguments passed to the logger constructor. Be careful, however, when using non-constant expressions and references to objects as constructor arguments, since the arguments are evaluated only once and it is often difficult to tell the exact moment when it is done. The logger is constructed on the first request from whichever part of the application that has the knowledge of the logger declaration. It is up to user to make sure that all arguments have valid states at that point.
The third macro of this section provides maximum initialization flexibility, allowing the user to actually define the logic of creating the logger.
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT
(my_logger, src::severity_logger_mt)
{
// Do something that needs to be done on logger initialization,
// e.g. add a stop watch attribute.
src::severity_logger_mt< > lg;
lg.add_attribute("StopWatch", attrs::timer());
// The initializing routine must return the logger instance
return lg;
}
Like the BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS
macro, the initialization code is called only once, on the first request
of the logger.
Important | |
---|---|
Beware of One Definition Rule (ODR) issues. Regardless of the way of
logger declaration you choose, you should ensure that the
logger is declared in exactly the same way at all occurrences
and all symbol names involved in the declaration
resolve to the same entities. The latter includes the names
used within the initialization routine of the |
In order to alleviate ODR problems, it is possible to separate the logger declaration and its initialization routine. The library provides the following macros to achieve this:
BOOST_LOG_GLOBAL_LOGGER
provides the logger declaration. It can be used in a header, similarly
to the BOOST_LOG_INLINE_GLOBAL_LOGGER*
macros described above.
BOOST_LOG_GLOBAL_LOGGER_INIT
,
BOOST_LOG_GLOBAL_LOGGER_DEFAULT
and BOOST_LOG_GLOBAL_LOGGER_CTOR_ARGS
define the logger initialization routine. Their semantics and usage
is similar to the corresponding BOOST_LOG_INLINE_GLOBAL_LOGGER*
macros, for one exception: these macros
should be used in a single .cpp file.
For example:
// my_logger.h // =========== BOOST_LOG_GLOBAL_LOGGER(my_logger, src::severity_logger_mt) // my_logger.cpp // ============= #include "my_logger.h" BOOST_LOG_GLOBAL_LOGGER_INIT(my_logger, src::severity_logger_mt) { src::severity_logger_mt< > lg; lg.add_attribute("StopWatch", attrs::timer()); return lg; }
Regardless of the macro you used to declare the logger, you can acquire
the logger instance with the static get
function of the logger tag:
src::severity_logger_mt< >& lg = my_logger::get();
Further usage of the logger is the same as if it was a regular logger object of the corresponding type.
Warning | |
---|---|
It should be noted that it is not advised to use global loggers during the deinitialization stage of the application. Like any other global object in your application, the global logger may get destroyed before you try to use it. In such cases it's better to have a dedicated logger object that is guaranteed to be available as long as needed. |