• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  *
4  * HDF is dual licensed: you can use it either under the terms of
5  * the GPL, or the BSD license, at your option.
6  * See the LICENSE file in the root of this repository for complete details.
7  */
8 
9 #ifndef HC_GEN_LOG_H
10 #define HC_GEN_LOG_H
11 
12 #include <iostream>
13 #include <map>
14 #include <string>
15 
16 #include "option.h"
17 
18 namespace OHOS {
19 namespace Hardware {
20 
21 class Logger {
22 public:
Logger()23     Logger() : level_(INFO) {}
24 
~Logger()25     inline ~Logger()
26     {
27         if (level_ > INFO) {
28             ::std::cout << ERROR_COLOR_END;
29         }
30         if (level_ <= DEBUG && !Option::Instance().VerboseLog()) {
31             return;
32         }
33         ::std::cout << ::std::endl;
34     }
35 
36     template <typename T>
37     inline Logger &operator<<(const T &v)
38     {
39         if (level_ <= DEBUG && !Option::Instance().VerboseLog()) {
40             return *this;
41         }
42         ::std::cout << v;
43         return *this;
44     }
45 
Debug()46     inline Logger &Debug()
47     {
48         level_ = DEBUG;
49         if (Option::Instance().VerboseLog()) {
50             ShowLevel();
51         }
52         return *this;
53     }
54 
Info()55     inline Logger &Info()
56     {
57         level_ = INFO;
58         ShowLevel();
59         return *this;
60     }
61 
Warning()62     inline Logger &Warning()
63     {
64         level_ = WARNING;
65         ShowLevel();
66         return *this;
67     }
68 
Error()69     inline Logger &Error()
70     {
71         level_ = ERROR;
72         ShowLevel();
73         return *this;
74     }
75 
Fatal()76     inline Logger &Fatal()
77     {
78         level_ = FATAL;
79         ShowLevel();
80         return *this;
81     }
82 
83 private:
84     enum LogLevel {
85         NONE,
86         DEBUG,
87         INFO,
88         WARNING,
89         ERROR,
90         FATAL,
91     } level_;
92 
ShowLevel()93     void ShowLevel() const
94     {
95         static ::std::map<LogLevel, ::std::string> levelStrMap = {
96             {NONE,    ""       },
97             {DEBUG,   "Debug"  },
98             {INFO,    "Info"   },
99             {WARNING, "Warning"},
100             {ERROR,   "Error"  },
101             {FATAL,   "Fatal"  }
102         };
103         if (level_ > INFO) {
104             ::std::cout << ERROR_COLOR_PREFIX;
105         }
106         ::std::cout << "[" << levelStrMap[level_] << "] ";
107     }
108 
109 #ifdef OS_LINUX
110     static constexpr const char *ERROR_COLOR_PREFIX = "\033[31m";
111     static constexpr const char *ERROR_COLOR_END = "\033[0m";
112 #else
113     static constexpr const char *ERROR_COLOR_PREFIX = "";
114     static constexpr const char *ERROR_COLOR_END = "";
115 #endif
116 };
117 
118 } // namespace Hardware
119 } // namespace OHOS
120 #endif // HC_GEN_LOG_H
121