-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommon.py
64 lines (46 loc) · 1.17 KB
/
common.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
#!/usr/bin/env python2.7
#
# IMPORTS
#
import logging
import sys
import time
#
# CONSTANTS
#
LOG_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
LOG_FORMAT = '[%(asctime)s] %(levelname)s %(name)s %(funcName)s -- %(message)s'
#
# GLOBALS
#
__all__ = ['asciify', 'configure_logging', 'dt_to_ts', 'extract_attrs']
#
# METHODS
#
def asciify(s):
return ''.join([x if ord(x) < 128 else '?' for x in s])
def configure_logging(loggers, outfile, debug):
if outfile is None:
h = logging.StreamHandler(stream=sys.stdout)
else:
h = logging.handlers.WatchedFileHandler(outfile)
h.setLevel(logging.DEBUG) # enable everything; let the logger objects set the level threshold
h.setFormatter(logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_DATE_FORMAT))
for l in loggers:
l.handlers.append(h)
if debug:
l.setLevel(logging.DEBUG)
else:
l.setLevel(logging.INFO)
def dt_to_ts(dt):
return time.mktime(dt.timetuple())
def extract_attrs(obj, attrs, handlers):
""" Return a dict-view of an object, using only a whitelist of attributes. """
d = {}
for attr in attrs:
v = getattr(obj, attr)
f = handlers.get(attr)
if f:
v = f(v)
d[attr] = v
return d