C++ logger class ( Basic )

Spread the love

Sometimes its necessary to take everything we have covered already and write some basic sample class like this c++ logging example. There are logger classes that are generally used for debugging, timing performance and a plethora of other things.

Central to most logger or logging classes is the theme of being able to set the level of the warnings that the programmer wants to see while coding. These levels can run from mere info, to warning, to serious error. Generally, a programmer will want to see everything above a certain level.

We are intentionally going to write some sample code with logging only shown at one specific level. Have a good look at it, then rewrite it to show logging at or above the level indicated by the user while running the program below.

Capisce? ( Italian for do you understand? )

/* Example Logging class
   Will compile but has problems
*/ Needs your tender loving care

#include <iostream>

class Log{
    int logLevel, WARNING, ERROR, INFO;

    Log(int m_logLevel,int m_warning, int m_error, int m_info) 
        :logLevel(m_logLevel),WARNING(m_warning), ERROR(m_error), INFO(m_info) {};
    void setLevel(int warning_level){

    void Print(){

        std::cout << "\nWarning Log level set to : " << logLevel << std::endl;
        switch ( logLevel ){
            case 2:
                std::cout << "\nWarning: " << WARNING << std::endl;
            case 1:
                 std::cout  << " Info: "  << INFO << std::endl;
            case 3:      
                std::cout  << " ERROR: " << ERROR << std::endl;


int main()
    int warning_level;
    std::cout << "Set warning at \n";
    std::cin >> warning_level;
    Log log(2,2,3,1);
    // Suppose we did this -- "Log log;" -- would it work?    

Problems with the c++ logger class

If the class is instantiated as an object using the constructor Log log(); , it should fail.

  • Homework
  • Why should it fail?
  • What is the fix?
  • Did you already fix the warning levels problem? Inquiring minds want to know.