-
Notifications
You must be signed in to change notification settings - Fork 4
/
cee_formatter.py
73 lines (59 loc) · 1.99 KB
/
cee_formatter.py
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
import json
import logging
import traceback
from collections import OrderedDict
from datetime import date, datetime
IGNORED_FIELDS = (
'args',
'asctime',
'created',
'exc_info',
'levelno',
'module',
'msecs',
'message',
'msg',
'name',
'pathname',
'process',
'relativeCreated',
'thread',
)
class CEEFormatter(logging.Formatter):
def __init__(self, *args, **kwargs):
self.ignored_fields = kwargs.get('ignored_fields', IGNORED_FIELDS)
super(CEEFormatter, self).__init__(*args, **kwargs)
def jsonhandler(self, obj):
if isinstance(obj, datetime) and self.datefmt:
return obj.strftime(self.datefmt)
elif isinstance(obj, date) or isinstance(obj, datetime):
return obj.isoformat()
try:
return str(obj)
except Exception:
return '<object of type \'{}\' cannot be converted to str>'.format(
type(obj).__name__
)
def format(self, log_record):
record = OrderedDict()
record['time'] = datetime.utcfromtimestamp(log_record.created)
record['message'] = log_record.getMessage()
record['pid'] = log_record.process
record['tid'] = log_record.thread
record['level'] = log_record.levelname
record['logger'] = log_record.name
if log_record.exc_info:
record['exception'] = '\n'.join(
traceback.format_exception(*log_record.exc_info)
)
for k in sorted(log_record.__dict__.keys()):
if log_record.__dict__[k] is not None and k not in self.ignored_fields:
record[k] = log_record.__dict__[k]
if record['threadName'] == 'MainThread':
del record['threadName']
if record['processName'] == 'MainProcess':
del record['processName']
return '%s @cee: %s' % (
record['message'].replace('\n', ' '),
json.dumps(record, default=self.jsonhandler)
)