|
1
|
|
|
import logging |
|
2
|
|
|
import traceback |
|
3
|
|
|
import json |
|
4
|
|
|
import os |
|
5
|
|
|
import socket |
|
6
|
|
|
|
|
7
|
|
|
class JSONFormatter(object): |
|
8
|
|
|
|
|
9
|
|
|
def __init__(self, *args, **extra_tags): |
|
10
|
|
|
self.dumps = extra_tags.pop('dumps', lambda obj: json.dumps(obj, default=lambda obj: str(obj))) |
|
11
|
|
|
|
|
12
|
|
|
object.__init__(self, *args) |
|
13
|
|
|
self.extra_tags = extra_tags |
|
14
|
|
|
|
|
15
|
|
|
def format(self, record): |
|
16
|
|
|
|
|
17
|
|
|
if isinstance(record.msg, dict): |
|
18
|
|
|
data = record.msg |
|
19
|
|
|
elif isinstance(record.msg, (list, tuple)): |
|
20
|
|
|
data = {'items': record.msg} |
|
21
|
|
|
else: |
|
22
|
|
|
data = {'msg':record.msg} |
|
23
|
|
|
|
|
24
|
|
|
kwargs = self.extra_tags.copy() |
|
25
|
|
|
|
|
26
|
|
|
data.update(logLevel=record.levelname, |
|
27
|
|
|
logModule=record.module, |
|
28
|
|
|
logName=record.name, |
|
29
|
|
|
pid=os.getpid(), |
|
30
|
|
|
**kwargs) |
|
31
|
|
|
|
|
32
|
|
|
if record.exc_info: |
|
33
|
|
|
etype, value, tb = record.exc_info |
|
34
|
|
|
tb = '\n'.join(traceback.format_exception(etype, value, tb)) |
|
35
|
|
|
data['exception'] = True |
|
36
|
|
|
data['traceback'] = tb |
|
37
|
|
|
|
|
38
|
|
|
msg = self.dumps(data) |
|
39
|
|
|
return msg |
|
40
|
|
|
|
|
41
|
|
|
class JSONSysLogFormatter(JSONFormatter): |
|
42
|
|
|
def __init__(self, appName, *args, **extra_tags): |
|
43
|
|
|
self.appName = appName |
|
44
|
|
|
JSONFormatter.__init__(self, *args, **extra_tags) |
|
45
|
|
|
|
|
46
|
|
|
def format(self, record): |
|
47
|
|
|
msg = JSONFormatter.format(self, record) |
|
48
|
|
|
return '%s %s' % (self.appName, msg) |
|
49
|
|
|
|
|
50
|
|
|
|
|
51
|
|
|
def syslog_handler(app_name='binstar-client'): |
|
52
|
|
|
|
|
53
|
|
|
address = None |
|
54
|
|
|
if os.path.exists('/dev/log'): |
|
55
|
|
|
address = '/dev/log' |
|
56
|
|
|
elif os.path.exists('/var/run/syslog'): |
|
57
|
|
|
address = '/var/run/syslog' |
|
58
|
|
|
else: |
|
59
|
|
|
address = ('localhost', 514) |
|
60
|
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
|
61
|
|
|
try: |
|
62
|
|
|
s.connect(address) |
|
63
|
|
|
except: |
|
64
|
|
|
return logging.NullHandler() |
|
65
|
|
|
|
|
66
|
|
|
hdlr = logging.handlers.SysLogHandler(address=address) |
|
67
|
|
|
hdlr.setLevel(logging.INFO) |
|
68
|
|
|
hdlr.setFormatter(JSONSysLogFormatter(app_name)) |
|
69
|
|
|
return hdlr |
|
70
|
|
|
|