1 /*
2  * Copyright 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef SYSTEM_KEYMASTER_LOGGER_H_
18 #define SYSTEM_KEYMASTER_LOGGER_H_
19 
20 #include <stdarg.h>
21 
22 namespace keymaster {
23 
24 class Logger {
25   public:
Logger()26     Logger() {}
~Logger()27     virtual ~Logger() {}
28 
29     enum LogLevel {
30         DEBUG_LVL,    // Messages used only for debugging
31         INFO_LVL,     // Informational messages; something is unusual but not wrong
32         WARNING_LVL,  // There's an indication of trouble, but it may be okay.
33         ERROR_LVL,    // A problem has occurred, but processing can continue
34         SEVERE_LVL,   // A severe problem has occurred; likely indicates a defect.
35     };
36 
37     virtual int log_msg(LogLevel level, const char* fmt, va_list args) const = 0;
38 
39     static int Log(LogLevel level, const char* fmt, va_list args);
40 
41     __attribute__((format(printf, 2, 3))) static int Log(LogLevel level, const char* fmt, ...);
42     __attribute__((format(printf, 1, 2))) static int Debug(const char* fmt, ...);
43     __attribute__((format(printf, 1, 2))) static int Info(const char* fmt, ...);
44     __attribute__((format(printf, 1, 2))) static int Warning(const char* fmt, ...);
45     __attribute__((format(printf, 1, 2))) static int Error(const char* fmt, ...);
46     __attribute__((format(printf, 1, 2))) static int Severe(const char* fmt, ...);
47 
48   protected:
set_instance(Logger * logger)49     static void set_instance(Logger* logger) { instance_ = logger; }
50 
51   private:
52     // Disallow copying.
53     Logger(const Logger&);
54     void operator=(const Logger&);
55 
56     static Logger* instance_;
57 };
58 
59 #define __KM_STR(x) #x
60 #define __KM_STRINGIFY(x) __KM_STR(x)
61 #define __KM_FILE_LINE __FILE__ ", Line " __KM_STRINGIFY(__LINE__) ": "
62 
63 #define LOG_D(fmt, ...) Logger::Debug(__KM_FILE_LINE fmt, ##__VA_ARGS__)
64 #define LOG_I(fmt, ...) Logger::Info(__KM_FILE_LINE fmt, ##__VA_ARGS__)
65 #define LOG_W(fmt, ...) Logger::Warning(__KM_FILE_LINE fmt, ##__VA_ARGS__)
66 #define LOG_E(fmt, ...) Logger::Error(__KM_FILE_LINE fmt, ##__VA_ARGS__)
67 #define LOG_S(fmt, ...) Logger::Severe(__KM_FILE_LINE fmt, ##__VA_ARGS__)
68 
69 }  // namespace keymaster
70 
71 #endif  // SYSTEM_KEYMASTER_LOGGER_H_
72