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.
18 from logging import Formatter
57 HIGHLIGHT_TAG = "highlight"
58 ATTRIBUTE_TAG = "attribute"
63 def colored(text, color=None, on_color=None, attrs=None):
64 # It can't support windows system cmd right now!
65 # TODO: colered output on windows system cmd
66 if os.name in ('nt', 'ce'):
69 if isinstance(attrs, str):
72 if os.getenv('ANSI_COLORS_DISABLED', None) is None:
73 fmt_str = '\033[%dm%s'
74 if color is not None and isinstance(color, str):
75 text = fmt_str % (COLORS.get(color, 0), text)
77 if on_color is not None and isinstance(on_color, str):
78 text = fmt_str % (HIGHLIGHTS.get(on_color, 0), text)
82 text = fmt_str % (ATTRIBUTES.get(attr, 0), text)
84 # keep origin color for tail spaces
89 class BaseColorFormatter(Formatter):
91 def __init__(self, fmt=None, datefmt=None, colorfmt=None, style="%"):
92 if sys.version_info > (3, 2):
93 super(BaseColorFormatter, self).__init__(
94 fmt=fmt, datefmt=datefmt, style=style)
95 elif sys.version_info > (2, 7):
96 super(BaseColorFormatter, self).__init__(fmt, datefmt)
98 Formatter.__init__(self, fmt, datefmt)
101 if sys.version_info > (3, 2):
102 if self.style not in logging._STYLES:
103 raise ValueError('Style must be one of: %s' % ','.join(
104 logging._STYLES.keys()))
106 self.colorfmt = colorfmt
108 def _parseColor(self, record):
110 color formatter for instance:
115 "highlight":"<HIGHLIGHTS>",
116 "attribute":"<ATTRIBUTES>",
120 :return: text color, background color, text attribute
122 if self.colorfmt and isinstance(self.colorfmt, dict):
124 level = record.levelname
125 colors = self.colorfmt.get(level, None)
127 if colors is not None and isinstance(colors, dict):
128 return colors.get(COLOR_TAG, None), \
129 colors.get(HIGHLIGHT_TAG, None), \
130 colors.get(ATTRIBUTE_TAG, None)
132 return None, None, None
134 def format(self, record):
136 if sys.version_info > (2, 7):
137 s = super(BaseColorFormatter, self).format(record)
139 s = Formatter.format(self, record)
140 color, on_color, attribute = self._parseColor(record)
141 return colored(s, color, on_color, attrs=attribute)