Search
 
SCRIPT & CODE EXAMPLE
 

CPP

c++ logger class example

/*
Usage:
*/
#include "Log.h"

int main(int argc, char** argv) {
    //Config: -----(optional)----
    structlog LOGCFG = {};
    LOGCFG.headers = false; 
    LOGCFG.level = DEBUG;
    //---------------------------
    LOG(INFO) << "Main executed with " << (argc - 1) << " arguments";
}

/* 
 * File:   Log.h
 * Author: Alberto Lepe <dev@alepe.com>
 *
 * Created on December 1, 2015, 6:00 PM
 */
#ifndef LOG_H
#define LOG_H

#include <iostream>

using namespace std;

enum typelog {
    DEBUG,
    INFO,
    WARN,
    ERROR
};

struct structlog {
    bool headers = false;
    typelog level = WARN;
};

extern structlog LOGCFG;

class LOG {
public:
    LOG() {}
    LOG(typelog type) {
        msglevel = type;
        if(LOGCFG.headers) {
            operator << ("["+getLabel(type)+"]");
        }
    }
    ~LOG() {
        if(opened) {
            cout << endl;
        }
        opened = false;
    }
    template<class T>
    LOG &operator<<(const T &msg) {
        if(msglevel >= LOGCFG.level) {
            cout << msg;
            opened = true;
        }
        return *this;
    }
private:
    bool opened = false;
    typelog msglevel = DEBUG;
    inline string getLabel(typelog type) {
        string label;
        switch(type) {
            case DEBUG: label = "DEBUG"; break;
            case INFO:  label = "INFO "; break;
            case WARN:  label = "WARN "; break;
            case ERROR: label = "ERROR"; break;
        }
        return label;
    }
};

#endif  /* LOG_H */
Comment

PREVIOUS NEXT
Code Example
Cpp :: cout c++ 
Cpp :: how to append to a vector c++ 
Cpp :: stoi() c++ 
Cpp :: cpp create lambda with recursion 
Cpp :: calculate factorial 
Cpp :: inline function in c++ 
Cpp :: c++ ternary operator 
Cpp :: to lowercase c++ 
Cpp :: methods available for a stl vector 
Cpp :: pragma cpp 
Cpp :: vector to string cpp 
Cpp :: fizzbuzz c++ 
Cpp :: 2d vector in cpp 
Cpp :: c pre-processor instructions 
Cpp :: c++ open file explorer 
Cpp :: how to get hcf of two number in c++ 
Cpp :: life the universe and everything solution c++ 
Cpp :: list in c++ 
Cpp :: print stack without pop c++ 
Cpp :: c++ access second last element of vector 
Cpp :: char to string c++ 
Cpp :: Subarray with given sum in c++ 
Cpp :: system cpp 
Cpp :: data types in c++ 
Cpp :: qt make widget ignore mouse events 
Cpp :: converting decimal to binary in cpp 
Cpp :: string erase 
Cpp :: Initialize Vector Iterator Through Vector Using Iterators 
Cpp :: C++ String Concatenation Example 
Cpp :: how to declare an enum variable c++ 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =