Logging is both a crucial technique during development and a great tool for investigating problems which arise while running software on a client's system. One of the major benefits of logging is that users of software can provide helpful information to software maintainers by simply delivering the logged data — a job for which they don't need to know anything about programming languages, debuggers, and the like.
Of course, there are numerous implementations of logging, which begs the questions "So why do we need yet another logging utility?" One reason is that many logging tools suffer from drawbacks of one kind or another:
- Logging can consume a lot of resources even if it is fully disabled in release builds. Log messages are still part of the build and in case of special debug messages (e.g., for a proprietary algorithm) it enables reverse-engineering of your code. Moreover, the logging framework can be ever present, due to disabling logging only at runtime
- Preprocessor implemented logging often has side effects. For instance, if you want to call a function always and for debugging purpose you print its return value with the help of a logging macro like
LOGGING(ret=f())the function is only called if logging is active. If the macro is empty defined to disable logging, the function will never be called. Such Heisenbugs are hard to find.
- Adding new features like different back-ends (sinks) or customized prefixes on logging messages requires careful study.
So what are the feature requirements that a basic logging framework should have?
- Easy to use (maybe with the typical behavior of operator<<).
- Easy to extend
- Possible to enable/disable certain parts both at compile time and at runtime, depending on the configuration.
- Possible to be disabled at compile time, leading to zero overhead at runtime. Thus, neither code nor memory is wasted
- Efficient and economical in terms of resource so that it can be used in resource-constrained environments (like microcontrollers).
- Able to avoid macro-related pitfalls in logging statements
In this article I present a flexible, highly configurable, and easily customizable logging framework that uses standard C++ in meeting these requirements The complete source code and related files are available here.
The following code snippet illustrates a typical use case:
log::emit() << "Hello World!" << log::endl;
This example outputs "Hello World! with linefeed and is easy to use (Requirement #1). Can you also see similarities to
std::cout? I use
log instead of
emit() instead of
emit() is a function returning "something", not an object like
cout. However, it is usable with
operator<<() for outputting logging data. Furthermore, no macro is used at the statement level (Requirement #8).