a322e29eb972e5c9b063258173a5545837f7098e
[logging-analytics.git] / pylog / onaplogging / markerFormatter.py
1 # Copyright 2018 ke liang <lokyse@163.com>.
2 #
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
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import sys
16 import logging
17 from .marker import MARKER_TAG
18 from .marker import Marker
19 from .colorFormatter import BaseColorFormatter
20
21
22 class MarkerFormatter(BaseColorFormatter):
23
24     def __init__(self, fmt=None, datefmt=None, colorfmt=None, style='%'):
25
26         if sys.version_info > (3, 2):
27             super(MarkerFormatter, self).__init__(
28                 fmt=fmt, datefmt=datefmt, colorfmt=colorfmt, style=style)
29         elif sys.version_info > (2, 7):
30             super(MarkerFormatter, self).__init__(
31                 fmt=fmt, datefmt=datefmt, colorfmt=colorfmt)
32         else:
33             BaseColorFormatter.__init__(self, fmt, datefmt, colorfmt)
34
35         self._marker_tag = "%(marker)s"
36
37         if self.style == "{":
38             self._marker_tag = "{marker}"
39         elif self.style == "$":
40             self._marker_tag = "${marker}"
41
42         self._tmpFmt = self._fmt
43
44     def format(self, record):
45
46         try:
47             if self._fmt.find(self._marker_tag) != -1 \
48                     and hasattr(record, MARKER_TAG):
49                 marker = getattr(record, MARKER_TAG)
50
51                 if isinstance(marker, Marker):
52                     self._fmt = self._fmt.replace(
53                         self._marker_tag, marker.getName())
54             elif self._fmt.find(self._marker_tag) != -1 \
55                     and not hasattr(record, MARKER_TAG):
56
57                 self._fmt = self._fmt.replace(self._marker_tag, "")
58
59             if sys.version_info > (3, 2):
60                 self._style = logging._STYLES[self.style][0](self._fmt)
61
62             if sys.version_info > (2, 7):
63                 return super(MarkerFormatter, self).format(record)
64             else:
65                 return BaseColorFormatter.format(self, record)
66
67         finally:
68             self._fmt = self._tmpFmt