1 # Copyright 2018 ke liang <lokyse@163.com>.
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.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
16 from logging import LogRecord
17 from typing import Optional
19 from onaplogging.utils.styles import MARKER_OPTIONS
20 from onaplogging.utils.system import is_above_python_2_7, is_above_python_3_2
22 from .marker import Marker, MARKER_TAG
23 from .colorFormatter import BaseColorFormatter
26 class MarkerFormatter(BaseColorFormatter):
27 """Formats coloring styles based on a marker.
29 If `fmt` is not supplied, the `style` is used.
34 marker_tag: a marker to be applied.
35 temp_fmt : keeps initial format to be reset to after formatting.
37 fmt : human-readable format. Defaults to None.
38 datefmt : ISO8601-like (or RFC 3339-like) format. Defaults to None.
39 colorfmt : color schemas for logging levels. Defaults to None.
40 style : '%', '{' or '$' formatting. Defaults to '%'.
47 return self._marker_tag
55 def marker_tag(self, value):
57 self._marker_tag = value
60 def temp_fmt(self, value):
62 self._temp_fmt = value
65 fmt=None, # type: Optional[str]
66 datefmt=None, # type: Optional[str]
67 colorfmt=None, # type: Optional[dict]
68 style='%'): # type: Optional[str]
70 if is_above_python_3_2():
71 super(MarkerFormatter, self).\
72 __init__(fmt=fmt, # noqa: E122
75 style=style) # added in Python 3.2+
77 elif is_above_python_2_7():
78 super(MarkerFormatter, self).\
79 __init__(fmt=fmt, # noqa: E122
85 __init__(self, fmt, datefmt, colorfmt) # noqa: E122
87 self.marker_tag = MARKER_OPTIONS[self.style]
88 self.temp_fmt = self._fmt
90 def format(self, record):
91 # type: (LogRecord) -> str
94 Use it to apply the marker from the LogRecord record to the formatter
98 record : an instance of a logged event.
100 str : "colored" text (formatted text).
104 if self._fmt.find(self.marker_tag) != -1 and \
105 hasattr(record, MARKER_TAG):
106 marker = getattr(record, MARKER_TAG)
108 if isinstance(marker, Marker):
109 self._fmt = self._fmt.replace(self.marker_tag,
112 elif self._fmt.find(self.marker_tag) != -1 and \
113 not hasattr(record, MARKER_TAG):
114 self._fmt = self._fmt.replace(self.marker_tag, "")
116 if is_above_python_3_2():
117 StylingClass = logging._STYLES[self.style][0]
118 self.style = StylingClass(self._fmt)
120 if is_above_python_2_7():
121 # includes Python 3.2+ style attribute
122 return super(MarkerFormatter, self).format(record)
124 return BaseColorFormatter.format(self, record)
127 self._fmt = self.temp_fmt