d0da695e388939c8668bbc6add49caef5ad40ad3
[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 logging
16 from logging import LogRecord
17 from typing import Optional
18
19 from onaplogging.utils.styles import MARKER_OPTIONS
20 from onaplogging.utils.system import is_above_python_2_7, is_above_python_3_2
21
22 from .marker import Marker, MARKER_TAG
23 from .colorFormatter import BaseColorFormatter
24
25
26 class MarkerFormatter(BaseColorFormatter):
27     """Formats coloring styles based on a marker.
28
29     If `fmt` is not supplied, the `style` is used.
30
31     Extends:
32         BaseColorFormatter
33     Properties:
34         marker_tag: a marker to be applied.
35         temp_fmt  : keeps initial format to be reset to after formatting.
36     Args:
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 '%'.
41                       Added in Python 3.2.
42     """
43
44     @property
45     def marker_tag(self):
46         # type: () -> str
47         return self._marker_tag
48
49     @property
50     def temp_fmt(self):
51         # type: () -> str
52         return self._temp_fmt
53
54     @marker_tag.setter
55     def marker_tag(self, value):
56         # type: (str) -> None
57         self._marker_tag = value
58
59     @temp_fmt.setter
60     def temp_fmt(self, value):
61         # type: (str) -> None
62         self._temp_fmt = value
63
64     def __init__(self,
65                  fmt=None,          # type: Optional[str]
66                  datefmt=None,      # type: Optional[str]
67                  colorfmt=None,     # type: Optional[dict]
68                  style='%'):        # type: Optional[str]
69
70         if is_above_python_3_2():
71             super(MarkerFormatter, self).\
72             __init__(fmt=fmt,  # noqa: E122
73                      datefmt=datefmt,
74                      colorfmt=colorfmt,
75                      style=style)  # added in Python 3.2+
76
77         elif is_above_python_2_7():
78             super(MarkerFormatter, self).\
79             __init__(fmt=fmt,  # noqa: E122
80                      datefmt=datefmt,
81                      colorfmt=colorfmt)
82
83         else:
84             BaseColorFormatter.\
85             __init__(self, fmt, datefmt, colorfmt)  # noqa: E122
86
87         self.marker_tag = MARKER_OPTIONS[self.style]
88         self.temp_fmt = self._fmt
89
90     def format(self, record):
91         # type: (LogRecord) -> str
92         """Marker formatter.
93
94         Use it to apply the marker from the LogRecord record to the formatter
95         string `fmt`.
96
97         Args:
98             record  : an instance of a logged event.
99         Returns:
100             str     : "colored" text (formatted text).
101         """
102         try:
103
104             if  self._fmt.find(self.marker_tag) != -1 and \
105                 hasattr(record, MARKER_TAG):
106                 marker = getattr(record, MARKER_TAG)
107
108                 if isinstance(marker, Marker):
109                     self._fmt = self._fmt.replace(self.marker_tag,
110                                                   marker.name)
111
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, "")
115
116             if is_above_python_3_2():
117                 StylingClass = logging._STYLES[self.style][0]
118                 self.style = StylingClass(self._fmt)
119
120             if is_above_python_2_7():
121                 # includes Python 3.2+ style attribute
122                 return super(MarkerFormatter, self).format(record)
123             else:
124                 return BaseColorFormatter.format(self, record)
125
126         finally:
127             self._fmt = self.temp_fmt