1 # Copyright (c) 2018 VMware, Inc.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 class MDCFormatter(logging.Formatter):
18 A custom MDC formatter to prepare Mapped Diagnostic Context
19 to enrich log message.
22 def __init__(self, fmt=None, mdcfmt=None, datefmt=None):
24 :param fmt: build-in format string contains standard
25 Python %-style mapping keys
26 :param mdcFmt: mdc format with '{}'-style mapping keys
27 :param datefmt: Date format to use
30 super(MDCFormatter, self).__init__(fmt=fmt, datefmt=datefmt)
31 self._tmpfmt = self._fmt
35 self._mdcFmt = '{reqeustID}'
39 maximum barce match algorithm to find the mdc key
40 :return: key in brace and key not in brace,such as ({key}, key)
48 for index, v in enumerate(target):
59 keys.append(target[start:end + 1])
63 keys = filter(lambda x: x[1:-1].strip('\n \t ') != "", keys)
66 words = map(lambda x: x[1:-1], keys)
70 def _replaceStr(self, keys):
74 fmt = fmt.replace(i, i[1:-1] + "=" + i)
78 def format(self, record):
80 Find mdcs in log record extra field, if key form mdcFmt dosen't
81 contains mdcs, the values will be empty.
82 :param record: the logging record instance
85 the mdcs dict in logging record is
86 {'key1':'value1','key2':'value2'}
87 the mdcFmt is" '{key1} {key3}'
88 the output of mdc message: 'key1=value1 key3='
91 mdcIndex = self._fmt.find('%(mdc)s')
93 return super(MDCFormatter, self).format(record)
95 mdcFmtkeys, mdcFmtWords = self._mdcfmtKey()
96 if mdcFmtWords is None:
98 self._fmt = self._fmt.replace("%(mdc)s", "")
99 return super(MDCFormatter, self).format(record)
101 mdc = record.__dict__.get('mdc', None)
103 for i in mdcFmtWords:
111 mdcstr = self._replaceStr(keys=mdcFmtkeys).format(**res)
112 self._fmt = self._fmt.replace("%(mdc)s", mdcstr)
113 s = super(MDCFormatter, self).format(record)
116 except KeyError as e:
117 print ("The mdc key %s format is wrong" % e.message)
123 self._fmt = self._tmpfmt