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 """Structured logging library with Mapped Diagnostic Context
18 Outputs the log entries to standard out in structured format, json currently.
19 Severity based filtering.
20 Supports Mapped Diagnostic Context (MDC).
22 Set MDC pairs are automatically added to log entries by the library.
24 from typing import TypeVar
25 from enum import IntEnum
32 """Severity levels of the log messages."""
39 LEVEL_STRINGS = {Level.DEBUG: "DEBUG",
41 Level.WARNING: "WARNING",
45 Value = TypeVar('Value', str, int)
49 """Initialize the mdclogging module.
50 Calling of the function is optional. If not called, the process name
51 (sys.argv[0]) is used by default.
54 name -- name of the component. The name will appear as part of the log
57 def __init__(self, name: str = sys.argv[0], level: Level = Level.DEBUG):
58 """Initialize a Logger instance.
61 name -- name of the component. The name will appear as part of the
65 self.current_level = level
68 def _output_log(self, log: str):
69 """Output the log, currently to stdout."""
72 def log(self, level: Level, message: str):
75 Logs the message with the given severity if it is equal or higher than
76 the current logging level.
79 level -- severity of the log message
80 message -- log message
82 if level >= self.current_level:
84 log_entry["ts"] = int(round(time.time() * 1000))
85 log_entry["crit"] = LEVEL_STRINGS[level]
86 log_entry["id"] = self.procname
87 log_entry["mdc"] = self.mdc
88 log_entry["msg"] = message
89 self._output_log(json.dumps(log_entry))
91 def error(self, message: str):
92 """Log an error message. Equals to log(ERROR, msg)."""
93 self.log(Level.ERROR, message)
95 def warning(self, message: str):
96 """Log a warning message. Equals to log(WARNING, msg)."""
97 self.log(Level.WARNING, message)
99 def info(self, message: str):
100 """Log an info message. Equals to log(INFO, msg)."""
101 self.log(Level.INFO, message)
103 def debug(self, message: str):
104 """Log a debug message. Equals to log(DEBUG, msg)."""
105 self.log(Level.DEBUG, message)
107 def set_level(self, level: Level):
108 """Set current logging level.
111 level -- logging level. Log messages with lower severity will be
115 self.current_level = Level(level)
119 def get_level(self) -> Level:
120 """Return the current logging level."""
121 return self.current_level
123 def add_mdc(self, key: str, value: Value):
124 """Add a logger specific MDC.
126 If an MDC with the given key exists, it is replaced with the new one.
127 An MDC can be removed with remove_mdc() or clean_mdc().
133 self.mdc[key] = value
135 def get_mdc(self, key: str) -> Value:
136 """Return logger's MDC value with the given key or None."""
142 def remove_mdc(self, key: str):
143 """Remove logger's MDC with the given key."""
150 """Remove all MDCs of the logger instance."""