Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Small logger class

Tags:

c++

logging

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.

like image 565
herzl shemuelian Avatar asked Feb 17 '11 11:02

herzl shemuelian


People also ask

What is log class C++?

In C++, an error logger class is typically used to track errors, warnings, and status messages at runtime.

How do you create a Logger class in C++?

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.

What is a logger class?

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.

How do I create a log file in CPP?

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.


1 Answers

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.

like image 59
Pedro d'Aquino Avatar answered Sep 22 '22 18:09

Pedro d'Aquino