-
Notifications
You must be signed in to change notification settings - Fork 0
/
log_help.py
100 lines (87 loc) · 2.66 KB
/
log_help.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
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
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import logging
LG = logging.getLogger(__name__) # Logger for this module
#LlG = logging.getLogger('perform')
#fh = logging.FileHandler('/tmp/performance.log',mode='w')
#fmt = logging.Formatter('%(asctime)s %(name)s:%(levelname)s - %(message)s')
#fh.setFormatter(fmt)
#fh.setLevel(logging.DEBUG)
#LlG.addHandler(fh)
def screen_handler(lg=None,lv='debug',fmt='%(name)s -%(levelname)s- %(message)s'):
"""
This function adds a screenHandler to a given logger. If no logger is
specified, just return the handler
"""
if lv == 'debug': lv = logging.DEBUG
elif lv == 'info': lv = logging.INFO
elif lv == 'warning': lv = logging.WARNING
elif lv == 'error': lv = logging.ERROR
elif lv == 'critical': lv = logging.CRITICAL
sh = logging.StreamHandler()
sh.setLevel(lv)
fmt = logging.Formatter(fmt)
sh.setFormatter(fmt)
if lg != None: lg.addHandler(sh)
return sh
def log2screen(lg,lv='info'):
""" This decorator adds *temporarily* a screenHandler to a given logger """
def do_it(wrapped):
def inner(*args, **kwargs):
sh = screen_handler(lg,lv=lv) # add ScreenHandler
ret = wrapped(*args, **kwargs)
lg.removeHandler(sh) # remove ScreenHandler
return ret
return inner
return do_it
def disable(lg):
"""
Temporarily raise the log level to CRITICAL to avoid over logging
"""
def do_it(wrapped):
def inner(*args, **kwargs):
lv = lg.getEffectiveLevel()
lg.setLevel(logging.CRITICAL)
ret = wrapped(*args, **kwargs)
lg.setLevel(lv)
return ret
return inner
return do_it
def disable2(lg):
"""
Temporarily raise the log level to INFO to avoid over logging
"""
def do_it(wrapped):
def inner(*args, **kwargs):
lv = lg.getEffectiveLevel()
lg.setLevel(logging.INFO)
ret = wrapped(*args, **kwargs)
lg.setLevel(lv)
return ret
return inner
return do_it
## Timer Decorator
from time import time
def timer(lg):
"""
Logs the execution time of a certain funcion to the provided logger
"""
def real_timer(wrapped):
def inner(*args, **kwargs):
t = time()
ret = wrapped(*args, **kwargs)
lg.debug('Time for '+wrapped.__name__+': %ss'%(time()-t))
return ret
return inner
return real_timer
def deprecated(lg):
"""
Issues a warning when using a deprecated function
"""
def wrapper(wrapped):
def inner(*args, **kwargs):
lg.warning('Deprecated use of '+wrapped.__name__)
ret = wrapped(*args, **kwargs)
return ret
return inner
return wrapper