forked from pfalcon/pycopy-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
240 lines (182 loc) · 6 KB
/
__init__.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import utime
import uio
import sys
CRITICAL = 50
ERROR = 40
WARNING = 30
INFO = 20
DEBUG = 10
NOTSET = 0
_level_dict = {
CRITICAL: "CRITICAL",
ERROR: "ERROR",
WARNING: "WARNING",
INFO: "INFO",
DEBUG: "DEBUG",
}
class Logger:
level = NOTSET
def __init__(self, name):
self.name = name
self.handlers = None
def _level_str(self, level):
l = _level_dict.get(level)
if l is not None:
return l
return "LVL%s" % level
def setLevel(self, level):
self.level = level
def isEnabledFor(self, level):
return level >= (self.level or _level)
def log(self, level, msg, *args):
if level >= (self.level or _level):
record = LogRecord(
self.name, level, None, None, msg, args, None, None, None
)
if self.handlers:
for hdlr in self.handlers:
hdlr.emit(record)
def debug(self, msg, *args):
self.log(DEBUG, msg, *args)
def info(self, msg, *args):
self.log(INFO, msg, *args)
def warning(self, msg, *args):
self.log(WARNING, msg, *args)
def error(self, msg, *args):
self.log(ERROR, msg, *args)
def critical(self, msg, *args):
self.log(CRITICAL, msg, *args)
def exc(self, e, msg, *args):
buf = uio.StringIO()
sys.print_exception(e, buf)
self.log(ERROR, msg + "\n" + buf.getvalue(), *args)
def exception(self, msg, *args):
self.exc(sys.exc_info()[1], msg, *args)
def addHandler(self, hdlr):
if self.handlers is None:
self.handlers = []
self.handlers.append(hdlr)
_level = INFO
_loggers = {}
def getLogger(name=None):
if name is None:
name = "root"
if name in _loggers:
return _loggers[name]
if name == "root":
l = Logger(name)
sh = StreamHandler()
sh.formatter = Formatter()
l.addHandler(sh)
else:
l = Logger(name)
_loggers[name] = l
return l
def info(msg, *args):
getLogger(None).info(msg, *args)
def debug(msg, *args):
getLogger(None).debug(msg, *args)
def basicConfig(level=INFO, filename=None, stream=None, format=None, style="%"):
global _level
_level = level
if filename:
h = FileHandler(filename)
else:
h = StreamHandler(stream)
h.setFormatter(Formatter(format, style=style))
root.handlers.clear()
root.addHandler(h)
class Handler:
def __init__(self):
self.formatter = Formatter()
def setFormatter(self, fmt):
self.formatter = fmt
class StreamHandler(Handler):
def __init__(self, stream=None):
self._stream = stream or sys.stderr
self.terminator = "\n"
self.formatter = Formatter()
def emit(self, record):
self._stream.write(self.formatter.format(record) + self.terminator)
def flush(self):
pass
class FileHandler(Handler):
def __init__(self, filename, mode="a", encoding=None, delay=False):
super().__init__()
self.encoding = encoding
self.mode = mode
self.delay = delay
self.terminator = "\n"
self.filename = filename
self._f = None
if not delay:
self._f = open(self.filename, self.mode)
def emit(self, record):
if self._f is None:
self._f = open(self.filename, self.mode)
self._f.write(self.formatter.format(record) + self.terminator)
def close(self):
if self._f is not None:
self._f.close()
class Formatter:
converter = utime.localtime
def __init__(self, fmt=None, datefmt=None, style="%"):
self.fmt = fmt or "%(message)s"
self.datefmt = datefmt
if style not in ("%", "{"):
raise ValueError("Style must be one of: %, {")
self.style = style
def usesTime(self):
if self.style == "%":
return "%(asctime)" in self.fmt
elif self.style == "{":
return "{asctime" in self.fmt
def format(self, record):
# The message attribute of the record is computed using msg % args.
record.message = record.msg % record.args
# If the formatting string contains '(asctime)', formatTime() is called to
# format the event time.
if self.usesTime():
record.asctime = self.formatTime(record, self.datefmt)
# If there is exception information, it is formatted using formatException()
# and appended to the message. The formatted exception information is cached
# in attribute exc_text.
if record.exc_info is not None:
record.exc_text += self.formatException(record.exc_info)
record.message += "\n" + record.exc_text
# The record’s attribute dictionary is used as the operand to a string
# formatting operation.
if self.style == "%":
return self.fmt % record.__dict__
elif self.style == "{":
return self.fmt.format(**record.__dict__)
else:
raise ValueError(
"Style {0} is not supported by logging.".format(self.style)
)
def formatTime(self, record, datefmt=None):
assert datefmt is None # datefmt is not supported
ct = utime.localtime(record.created)
return "{0}-{1}-{2} {3}:{4}:{5}".format(*ct)
def formatException(self, exc_info):
raise NotImplementedError()
def formatStack(self, stack_info):
raise NotImplementedError()
root = getLogger()
class LogRecord:
def __init__(
self, name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None
):
ct = utime.time()
self.created = ct
self.msecs = (ct - int(ct)) * 1000
self.name = name
self.levelno = level
self.levelname = _level_dict.get(level, None)
self.pathname = pathname
self.lineno = lineno
self.msg = msg
self.args = args
self.exc_info = exc_info
self.func = func
self.sinfo = sinfo