Simple logger in c++

 

Introduction

Learning how to make a simple logger

Printing logs in program is important for debugging. A list of information we are looking for from the log:

  • Class name
  • Function name
  • Line number
  • Thread number
  • Log message
  • Log level
  • Log time

Elasticsearch and distributed system

In a distributed system, people employ a centralized service to look after all the logs for example: Elasticsearch

No matter how you process, keep, search your logs in the post operation process, you still want to have a way to manage to print the logs out from the application.

Why I create a private logger

A simple way is using the C++ boost library for logging. It could be my bias but I found that C++ boost library is big and sometime unpredictable. This is the reason I started to create  a simple logger for private usage. The logger

More details on private logger

This logger as a learning material I tried to handle 4 cases:

+----------------------+--------------+-----------------+
|          .           | With SStream | Without SStream |
+----------------------+--------------+-----------------+
| Inside class object  | Case 1       | Case 2          |
| Outside class object | Case 3       | Case 4          |
+----------------------+--------------+-----------------+

Case 1 and 2

20230413_055108_933 [MSG]                     Dummy::                   WhoAmI:    18,   120,Hello from: dummy_001

Case 3 and 4

20230413_055108_933 [MSG]                      main:    19,   120,Hello World from app: logger_demo

To have a better performance, there is a separated thread used for print the log to console or file. Here is another simple thread pool implementation to generalize the thread handling. Details

Project highlight

A simple message queue is created in this logger

m_cond.wait(lock, [&] { return m_jobQ.size() != 0 || !m_isRun.load(); });


Comments