1 # Copyright (c) 2019 AT&T Intellectual Property.
2 # Copyright (c) 2018-2019 Nokia.
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
16 # This source code is part of the near-RT RIC (RAN Intelligent Controller)
17 # platform project (RICP).
20 """Structured logging library with Mapped Diagnostic Context
22 Outputs the log entries to standard out in structured format, json currently.
23 Severity based filtering.
24 Supports Mapped Diagnostic Context (MDC).
26 Set MDC pairs are automatically added to log entries by the library.
28 from typing import TypeVar
29 from enum import IntEnum
34 import inotify.adapters
39 """Severity levels of the log messages."""
46 LEVEL_STRINGS = {Level.DEBUG: "DEBUG",
48 Level.WARNING: "WARNING",
52 Value = TypeVar('Value', str, int)
56 """Initialize the mdclogging module.
57 Calling of the function is optional. If not called, the process name
58 (sys.argv[0]) is used by default.
61 name -- name of the component. The name will appear as part of the log
64 def __init__(self, name: str = sys.argv[0], level: Level = Level.ERROR):
65 """Initialize a Logger instance.
68 name -- name of the component. The name will appear as part of the
72 self.current_level = level
76 # Pass configmap_monitor = True to monitor configmap to change logs dynamically using configmap
77 def mdclog_format_init(self,configmap_monitor=False):
79 self.mdc = {"PID":"","SYSTEM_NAME":"","HOST_NAME":"","SERVICE_NAME":"","CONTAINER_NAME":"","POD_NAME":""}
80 self.get_env_params_values()
82 self.filename = os.environ['CONFIG_MAP_NAME']
83 self.dirname = str(self.filename[:self.filename.rindex('/')])
84 if configmap_monitor == True:
85 self.register_log_change_notify()
87 except Exception as e:
88 print("Unable to Add Watch on ConfigMap File",e)
91 def _output_log(self, log: str):
92 """Output the log, currently to stdout."""
95 def log(self, level: Level, message: str):
98 Logs the message with the given severity if it is equal or higher than
99 the current logging level.
102 level -- severity of the log message
103 message -- log message
105 if level >= self.current_level:
107 log_entry["ts"] = int(round(time.time() * 1000))
108 log_entry["crit"] = LEVEL_STRINGS[level]
109 log_entry["id"] = self.procname
110 log_entry["mdc"] = self.mdc
111 log_entry["msg"] = message
112 self._output_log(json.dumps(log_entry))
114 def error(self, message: str):
115 """Log an error message. Equals to log(ERROR, msg)."""
116 self.log(Level.ERROR, message)
118 def warning(self, message: str):
119 """Log a warning message. Equals to log(WARNING, msg)."""
120 self.log(Level.WARNING, message)
122 def info(self, message: str):
123 """Log an info message. Equals to log(INFO, msg)."""
124 self.log(Level.INFO, message)
126 def debug(self, message: str):
127 """Log a debug message. Equals to log(DEBUG, msg)."""
128 self.log(Level.DEBUG, message)
130 def set_level(self, level: Level):
131 """Set current logging level.
134 level -- logging level. Log messages with lower severity will be
138 self.current_level = Level(level)
142 def get_level(self) -> Level:
143 """Return the current logging level."""
144 return self.current_level
146 def add_mdc(self, key: str, value: Value):
147 """Add a logger specific MDC.
149 If an MDC with the given key exists, it is replaced with the new one.
150 An MDC can be removed with remove_mdc() or clean_mdc().
156 self.mdc[key] = value
159 def get_env_params_values(self):
162 self.mdc['SYSTEM_NAME'] = os.environ['SYSTEM_NAME']
164 self.mdc['SYSTEM_NAME'] = ""
167 self.mdc['HOST_NAME'] = os.environ['HOST_NAME']
169 self.mdc['HOST_NAME'] = ""
172 self.mdc['SERVICE_NAME'] = os.environ['SERVICE_NAME']
174 self.mdc['SERVICE_NAME'] = ""
177 self.mdc['CONTAINER_NAME'] = os.environ['CONTAINER_NAME']
179 self.mdc['CONTAINER_NAME'] = ""
182 self.mdc['POD_NAME'] = os.environ['POD_NAME']
184 self.mdc['POD_NAME'] = ""
186 self.mdc['PID'] = os.getpid()
192 def update_mdc_log_level_severity(self,level):
193 severity_level = Level.DEBUG
196 print("Invalid Log Level defined in ConfigMap")
197 elif((level.upper() == "ERROR") or (level.upper() == "ERR" )):
198 severity_level = Level.ERROR
199 elif((level.upper() == "WARNING") or (level.upper() == "WARN")):
200 severity_level = Level.WARNING
201 elif(level.upper() == "INFO"):
202 severity_level = Level.INFO
203 elif(level.upper() == "DEBUG"):
204 severity_level = Level.DEBUG
206 self.set_level(severity_level)
212 def parse_file(self):
213 src = open(self.filename,'r')
216 if 'log-level:' in line:
217 level_tmp = str(line.split(':')[-1]).strip()
221 self.update_mdc_log_level_severity(level)
226 def monitor_loglevel_change_handler(self):
227 i = inotify.adapters.Inotify()
228 i.add_watch(self.dirname)
229 for event in i.event_gen():
230 if (event is not None) and ('IN_MODIFY' in str(event[1]) or 'IN_DELETE' in str(event[1])):
234 def register_log_change_notify(self):
235 t1 = threading.Thread(target=self.monitor_loglevel_change_handler)
239 except (KeyboardInterrupt, SystemExit):
240 cleanup_stop_thread()
246 def get_mdc(self, key: str) -> Value:
247 """Return logger's MDC value with the given key or None."""
253 def remove_mdc(self, key: str):
254 """Remove logger's MDC with the given key."""
261 """Remove all MDCs of the logger instance."""