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.
17 from logging import Formatter
19 from .utils import is_above_python_2_7, is_above_python_3_2
58 HIGHLIGHT_TAG = "highlight"
59 ATTRIBUTE_TAG = "attribute"
62 FMT_STR = "\033[%dm%s"
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'):
71 if isinstance(attrs, str):
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)
78 if on_color is not None and isinstance(on_color, str):
79 text = FMT_STR % (HIGHLIGHTS.get(on_color, 0), text)
83 text = FMT_STR % (ATTRIBUTES.get(attr, 0), text)
85 # keep origin color for tail spaces
90 class BaseColorFormatter(Formatter):
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)
99 Formatter.__init__(self, fmt, datefmt)
102 self.colorfmt = colorfmt
104 def _parseColor(self, record):
106 color formatter for instance:
111 "highlight":"<HIGHLIGHTS>",
112 "attribute":"<ATTRIBUTES>",
116 :return: text color, background color, text attribute
118 if self.colorfmt and isinstance(self.colorfmt, dict):
120 level = record.levelname
121 colors = self.colorfmt.get(level, None)
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)
128 return None, None, None
130 def format(self, record):
132 if sys.version_info > (2, 7):
133 s = super(BaseColorFormatter, self).format(record)
135 s = Formatter.format(self, record)
136 color, on_color, attribute = self._parseColor(record)
137 return colored(s, color, on_color, attrs=attribute)