c 2b 2b logger class example

Solutions on MaxInterview for c 2b 2b logger class example by the best coders in the world

showing results for - "c 2b 2b logger class example"
Solène
08 Oct 2020
1/*
2Usage:
3*/
4#include "Log.h"
5
6int main(int argc, char** argv) {
7    //Config: -----(optional)----
8    structlog LOGCFG = {};
9    LOGCFG.headers = false; 
10    LOGCFG.level = DEBUG;
11    //---------------------------
12    LOG(INFO) << "Main executed with " << (argc - 1) << " arguments";
13}
14
15/* 
16 * File:   Log.h
17 * Author: Alberto Lepe <dev@alepe.com>
18 *
19 * Created on December 1, 2015, 6:00 PM
20 */
21#ifndef LOG_H
22#define LOG_H
23
24#include <iostream>
25
26using namespace std;
27
28enum typelog {
29    DEBUG,
30    INFO,
31    WARN,
32    ERROR
33};
34
35struct structlog {
36    bool headers = false;
37    typelog level = WARN;
38};
39
40extern structlog LOGCFG;
41
42class LOG {
43public:
44    LOG() {}
45    LOG(typelog type) {
46        msglevel = type;
47        if(LOGCFG.headers) {
48            operator << ("["+getLabel(type)+"]");
49        }
50    }
51    ~LOG() {
52        if(opened) {
53            cout << endl;
54        }
55        opened = false;
56    }
57    template<class T>
58    LOG &operator<<(const T &msg) {
59        if(msglevel >= LOGCFG.level) {
60            cout << msg;
61            opened = true;
62        }
63        return *this;
64    }
65private:
66    bool opened = false;
67    typelog msglevel = DEBUG;
68    inline string getLabel(typelog type) {
69        string label;
70        switch(type) {
71            case DEBUG: label = "DEBUG"; break;
72            case INFO:  label = "INFO "; break;
73            case WARN:  label = "WARN "; break;
74            case ERROR: label = "ERROR"; break;
75        }
76        return label;
77    }
78};
79
80#endif  /* LOG_H */
81