This repository was archived by the owner on Nov 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLogger.py
More file actions
199 lines (165 loc) · 7.3 KB
/
Logger.py
File metadata and controls
199 lines (165 loc) · 7.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Translation Web Server
# Copyright © 2012 Luca Wehrstedt <luca.wehrstedt@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import os.path
import time
from traceback import format_tb
## ANSI utilities. See for reference:
# http://pueblo.sourceforge.net/doc/manual/ansi_color_codes.html
# http://en.wikipedia.org/wiki/ANSI_escape_code
#
ANSI_FG_COLORS = {'black': 30,
'red': 31,
'green': 32,
'yellow': 33,
'blue': 34,
'magenta': 35,
'cyan': 36,
'white': 37}
ANSI_BG_COLORS = {'black': 40,
'red': 41,
'green': 42,
'yellow': 43,
'blue': 44,
'magenta': 45,
'cyan': 46,
'white': 47}
ANSI_RESET_CMD = 0
ANSI_FG_DEFAULT_CMD = 39
ANSI_BG_DEFAULT_CMD = 49
ANSI_BOLD_ON_CMD = 1
ANSI_BOLD_OFF_CMD = 22
ANSI_FAINT_ON_CMD = 2
ANSI_FAINT_OFF_CMD = 22
ANSI_ITALICS_ON_CMD = 3
ANSI_ITALICS_OFF_CMD = 23
ANSI_UNDERLINE_ON_CMD = 4
ANSI_UNDERLINE_OFF_CMD = 24
ANSI_STRIKETHROUGH_ON_CMD = 9
ANSI_STRIKETHROUGH_OFF_CMD = 29
ANSI_INVERSE_ON_CMD = 7
ANSI_INVERSE_OFF_CMD = 27
# TODO missing:
# - distinction between single and double underline
# - "slow blink on", "rapid blink on" and "blink off"
# - "conceal on" and "conceal off" (also called reveal)
class LogFormatter(logging.Formatter):
"""A custom Formatter for our logs.
"""
def __init__(self, color=True, *args, **kwargs):
"""Initialize the formatter.
Based on the 'color' parameter we set the tags for many
elements of our formatted output.
"""
logging.Formatter.__init__(self, *args, **kwargs)
self.color = color
self.time_prefix = self.ansi_command(ANSI_BOLD_ON_CMD)
self.time_suffix = self.ansi_command(ANSI_BOLD_OFF_CMD)
self.cri_prefix = self.ansi_command(ANSI_BOLD_ON_CMD,
ANSI_FG_COLORS['white'],
ANSI_BG_COLORS['red'])
self.cri_suffix = self.ansi_command(ANSI_BOLD_OFF_CMD,
ANSI_FG_DEFAULT_CMD,
ANSI_BG_DEFAULT_CMD)
self.err_prefix = self.ansi_command(ANSI_BOLD_ON_CMD,
ANSI_FG_COLORS['red'])
self.err_suffix = self.ansi_command(ANSI_BOLD_OFF_CMD,
ANSI_FG_DEFAULT_CMD)
self.wrn_prefix = self.ansi_command(ANSI_BOLD_ON_CMD,
ANSI_FG_COLORS['yellow'])
self.wrn_suffix = self.ansi_command(ANSI_BOLD_OFF_CMD,
ANSI_FG_DEFAULT_CMD)
self.inf_prefix = self.ansi_command(ANSI_BOLD_ON_CMD,
ANSI_FG_COLORS['green'])
self.inf_suffix = self.ansi_command(ANSI_BOLD_OFF_CMD,
ANSI_FG_DEFAULT_CMD)
self.dbg_prefix = self.ansi_command(ANSI_BOLD_ON_CMD,
ANSI_FG_COLORS['blue'])
self.dbg_suffix = self.ansi_command(ANSI_BOLD_OFF_CMD,
ANSI_FG_DEFAULT_CMD)
def ansi_command(self, *args):
"""Produce the escape string that corresponds to the given
ANSI command.
"""
return "\033[%sm" % ';'.join([str(x)
for x in args]) if self.color else ''
def formatException(self, exc_info):
exc_type, exc_value, traceback = exc_info
result = "%sException%s %s.%s%s%s:\n\n %s\n\n" % \
(self.ansi_command(ANSI_BOLD_ON_CMD),
self.ansi_command(ANSI_BOLD_OFF_CMD),
exc_type.__module__,
self.ansi_command(ANSI_BOLD_ON_CMD),
exc_type.__name__,
self.ansi_command(ANSI_BOLD_OFF_CMD),
exc_value)
result += "%sTraceback (most recent call last):%s\n%s" % \
(self.ansi_command(ANSI_FAINT_ON_CMD),
self.ansi_command(ANSI_FAINT_OFF_CMD),
'\n'.join(
map(lambda a: self.ansi_command(ANSI_FAINT_ON_CMD) +
a + self.ansi_command(ANSI_FAINT_OFF_CMD),
''.join(format_tb(traceback)).strip().split('\n'))))
return result
def format(self, record):
"""Do the actual formatting.
Prepend a timestamp and an abbreviation of the logging level,
followed by the message, the request_body (if present) and the
exception details (if present).
"""
result = '%s%s.%03d%s' % (self.time_prefix,
self.formatTime(record, '%Y-%m-%d %H:%M:%S'), record.msecs,
self.time_suffix)
if record.levelno == logging.CRITICAL:
result += ' %s CRI %s ' % (self.cri_prefix, self.cri_suffix)
elif record.levelno == logging.ERROR:
result += ' %s ERR %s ' % (self.err_prefix, self.err_suffix)
elif record.levelno == logging.WARNING:
result += ' %s WRN %s ' % (self.wrn_prefix, self.wrn_suffix)
elif record.levelno == logging.INFO:
result += ' %s INF %s ' % (self.inf_prefix, self.inf_suffix)
else: # DEBUG
result += ' %s DBG %s ' % (self.dbg_prefix, self.dbg_suffix)
try:
message = record.getMessage()
except Exception, exc:
message = 'Bad message (%r): %r' % (exc, record.__dict__)
result += message.strip()
if "location" in record.__dict__:
result += "\n%s" % record.location.strip()
if "details" in record.__dict__:
result += "\n\n%s" % record.details.strip()
if record.exc_info:
result += "\n\n%s" % self.formatException(record.exc_info).strip()
return result.replace("\n", "\n ") + '\n'
# Create a global reference to the root logger.
logger = logging.getLogger()
# Catch all logging messages (we'll filter them on the handlers).
logger.setLevel(logging.DEBUG)
# Define the stream handler to output on stderr.
_stream_log = logging.StreamHandler()
_stream_log.setLevel(logging.WARNING)
_stream_log.setFormatter(LogFormatter(color=True))
logger.addHandler(_stream_log)
# Define the file handler to output on the specified log directory.
_file_log = logging.FileHandler(
os.path.join(os.path.dirname(__file__), "logs",
time.strftime("%Y-%m-%d-%H-%M-%S.log")))
_file_log.setLevel(logging.INFO)
_file_log.setFormatter(LogFormatter(color=False))
logger.addHandler(_file_log)