Pylog test suite
[logging-analytics.git] / pylog / onaplogging / colorFormatter.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 os
16 import sys
17 from logging import Formatter
18
19 from .utils import is_above_python_2_7, is_above_python_3_2
20
21
22 ATTRIBUTES = {
23     'normal': 0,
24     'bold': 1,
25     'underline': 4,
26     'blink': 5,
27     'invert': 7,
28     'hide': 8,
29
30 }
31
32
33 HIGHLIGHTS = {
34
35     'black': 40,
36     'red':  41,
37     'green': 42,
38     'yellow': 43,
39     'blue': 44,
40     'purple': 45,
41     'cyan': 46,
42     'white': 47,
43 }
44
45 COLORS = {
46
47     'black': 30,
48     'red': 31,
49     'green': 32,
50     'yellow': 33,
51     'blue': 34,
52     'purple': 35,
53     'cyan': 36,
54     'white': 37,
55 }
56
57 COLOR_TAG = "color"
58 HIGHLIGHT_TAG = "highlight"
59 ATTRIBUTE_TAG = "attribute"
60
61 RESET = "\033[0m"
62 FMT_STR = "\033[%dm%s"
63
64
65 def colored(text, color=None, on_color=None, attrs=None):
66     # It can't support windows system cmd right now!
67     # TODO: colered output on windows system cmd
68     if os.name in ('nt', 'ce'):
69         return text
70
71     if isinstance(attrs, str):
72         attrs = [attrs]
73
74     if os.getenv('ANSI_COLORS_DISABLED', None) is None:
75         if color is not None and isinstance(color, str):
76             text = FMT_STR % (COLORS.get(color, 0), text)
77
78         if on_color is not None and isinstance(on_color, str):
79             text = FMT_STR % (HIGHLIGHTS.get(on_color, 0), text)
80
81         if attrs is not None:
82             for attr in attrs:
83                 text = FMT_STR % (ATTRIBUTES.get(attr, 0), text)
84
85         #  keep origin color for tail spaces
86         text += RESET
87     return text
88
89
90 class BaseColorFormatter(Formatter):
91
92     def __init__(self, fmt=None, datefmt=None, colorfmt=None, style="%"):
93         if is_above_python_3_2():
94             super(BaseColorFormatter, self).__init__(
95                 fmt=fmt, datefmt=datefmt, style=style)
96         elif is_above_python_2_7():
97             super(BaseColorFormatter, self).__init__(fmt, datefmt)
98         else:
99             Formatter.__init__(self, fmt, datefmt)
100
101         self.style = style
102         self.colorfmt = colorfmt
103
104     def _parseColor(self, record):
105         """
106         color formatter for instance:
107         {
108             "logging-levelname":
109                 {
110                     "color":"<COLORS>",
111                     "highlight":"<HIGHLIGHTS>",
112                     "attribute":"<ATTRIBUTES>",
113                 }
114         }
115         :param record:
116         :return: text color, background color, text attribute
117         """
118         if self.colorfmt and isinstance(self.colorfmt, dict):
119
120             level = record.levelname
121             colors = self.colorfmt.get(level, None)
122
123             if colors is not None and isinstance(colors, dict):
124                 return colors.get(COLOR_TAG, None), \
125                        colors.get(HIGHLIGHT_TAG, None), \
126                        colors.get(ATTRIBUTE_TAG, None)
127
128         return None, None, None
129
130     def format(self, record):
131
132         if sys.version_info > (2, 7):
133             s = super(BaseColorFormatter, self).format(record)
134         else:
135             s = Formatter.format(self, record)
136         color, on_color, attribute = self._parseColor(record)
137         return colored(s, color, on_color, attrs=attribute)