-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.py
124 lines (104 loc) · 3.53 KB
/
log.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# coding: utf-8
# Simple logging module
import os, sys
import time
from functools import wraps
from datetime import datetime
sys.path.insert(0, os.path.dirname(__file__))
from color import colored
class Level(object):
"""
Log level
"""
class Label(object):
def __init__(self, name, level, color=None):
self.name = name
self.level = level
self.color = color
def __str__(self):
return self.name
def __cmp__(self, other):
if isinstance(other, Level.Label):
l = other.level
elif isinstance(other, int):
l = other
else:
raise TypeError
if self.level < other:
return -1
elif self.level > other:
return 1
else:
return 0
def __lt__(self, other): return self.__cmp__(other) < 0
def __gt__(self, other): return self.__cmp__(other) > 0
def __eq__(self, other): return self.__cmp__(other) == 0
def __ne__(self, other): return not self.__eq__(other)
def __le__(self, other): return self.__lt__(other) or self.__eq__(other)
def __ge__(self, other): return self.__gt__(other) or self.__eq__(other)
DEBUG = Label('DEBUG', 0)
INFO = Label('INFO', 1)
WARN = Label('WARN', 2, color='yellow')
ERROR = Label('ERROR', 3, color='red')
FATAL = Label('FATAL', 4, color='red')
@classmethod
def labelize(cls, level):
if level is None:
return cls.INFO
if isinstance(level, Level.Label):
return level
if isinstance(level, str):
if hasattr(cls, level):
return getattr(cls, level)
else:
raise ValueError('Undefined logging level: {}'.format(level))
raise TypeError
class Logger(object):
"""
Simple logging
[Usage]
from log import Logger
logger = Logger()
logger('message', level='DEBUG')
"""
def __init__(self, output=None, min_level=None, colored=True):
self.min_level = Level.labelize(min_level)
if output:
self.output = output
else:
self.output = sys.stdout
def write(self, message, level=None, color=None):
level = Level.labelize(level)
if level < self.min_level:
return
now = datetime.now().isoformat()
if color:
text = colored('{} [{}] {}\n'.format(now, level, message),
color=color)
else:
text = '{} [{}] {}\n'.format(now, level, message)
self.output.write(text)
def __call__(self, *args, **kwargs):
self.write(*args, **kwargs)
def logging(self, func):
@wraps(func)
def f(*args, **kwargs):
starttime = time.time()
self.write('Start: {}'.format(func.__name__))
error = None
try:
return func(*args, **kwargs)
except Exception as e:
error = e
finally:
elapsedtime = round(time.time() - starttime, 3)
if error:
self.write('End(Failed): {} ({}) Error={}'.format(
func.__name__, elapsedtime, error_message), color='red')
raise error
else:
self.write('End(Succeeded): {} ({})'.format(
func.__name__, elapsedtime), color='green')
return f
# Default logging object
LOG = Logger()