Thread Safe Simple Logger in C++11

This logger is an exercise in C++11 thread safety and a demonstration of Return Value Optimization (RVO)/Copy elision. Even though RVO behavior is not directly prescribed by the standard, most new compilers avoid unnecessary copies and destructor calls.

This code was tested on MSVC 2013 and on MinGW GCC 4.8.1 x64. Since RVO varies between different compilers and may be affected by compiler optimization flags, the code in this post is not guaranteed to work on all systems in its current state.

My ideal logger for small scale C++ projects should have a very simple usage as demonstrated below.

In order to implement the functionality described in the code above in a thread safe manner we need to instantiate an object whose life span is contained within only the log line. When the temporary object is destroyed the constructed log message is passed to the “main logger” object which takes care of thread safety.

To make life easier I’ve decided to create a class derived from the std::stringstream that will be used to instantiate the temporary object. Class std::stringstream removes the headache of having to write the parsing code.

Besides being derived from std::stringstream, logstream class retains a reference to the logger object as well as the user specified message log level. When the logstream object is destroyed its destructor calls logger::log() method with the arguments of the log message level and the parsed log message.

The most important parts of the logger class are the overloaded function call operator which creates and returns the logstream object, and the logger::log() method which is called from logstream object destructor. The logger class also makes use of a std::mutex class that provides thread safety when logging from multiple threads.

Since I wanted to make this logger simple it does not contain external configuration, log rotation, or a thread safe factory. You may download the projects for Code::Blocks and Visual Studio 2013 by clicking the links below.

Download SimpleLogger Code::Blocks
Download SimpleLogger MSVC2013