I am looking for a small lightweight logging system in c++. I have found some existing frameworks but I don't need all of their features at this point in time. I primarily am looking for a small system that can for example configure the log level output file. I am looking for an existing solution as I don't want to reinvent the wheel.
In C++, an error logger class is typically used to track errors, warnings, and status messages at runtime.
We will start by implementing the logger class and create a parametrized ctor. According to the RAII concept, this ctor will initialize the file stream. The second resource, the locking object, is needed in the output function. This output function which will add a logging message can be called by different threads.
A Logger object is used to log messages for a specific system or application component. Loggers are normally named, using a hierarchical dot-separated namespace. Logger names can be arbitrary strings, but they should normally be based on the package name or class name of the logged component, such as java.net or javax.
Use normal fstream objects. The log function should open the log file, write the log entry … This has not been compiled or tested, so it might or might not contain bugs. void log(const char*msg) { time_t now = time(0); struct tm* tm = localtime(&now); ofstream out( "logfile.
I strongly recommend this simple logging system: http://www.drdobbs.com/cpp/201804215. It is composed of a single header file. I have successfully used it on Linux, Windows and Mac OS X.
You write to the log like this:
FILE_LOG(logWARNING) << "Ops, variable x should be " << expectedX << "; is " << realX;
I really like the stream syntax. It is unobtrusive, typesafe and expressive. The logging framework automatically adds a \n
at the end of the line, plus date, time and indentation.
Configuring the logs is pretty easy:
FILELog::ReportingLevel() = logDEBUG3; FILE* log_fd = fopen( "mylogfile.txt", "w" ); Output2FILE::Stream() = log_fd;
This framework is also easy to extend. At work, we have recently made some adaptations to it so that it now uses an std::ofstream
instead of a FILE*
. As a result, we are now able to add nice features such as encrypting the logs, by chaining the streams.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With