-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.py
69 lines (51 loc) · 1.83 KB
/
logger.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
import sys
from typing import IO, Optional, Any
class Logger:
_output = None
def __init__(self, output: Optional[IO] = None):
self._output = output
def console(self, message: str, end: str = '\n'):
"""
Write message with end as the last character to `sys.stdout`, if it is a terminal.
:param message: The message to write.
:param end: The last character.
"""
if self._output is None and sys.stdout.isatty():
sys.stdout.write(message + end)
def log(self, prefix: str, message: str):
"""
Write the given message appended to the prefix to the logfile or stdout.
:param prefix: A prefix.
:param message: The message to write.
"""
if self._output is None:
print(prefix + ' ' + message)
sys.stdout.flush()
else:
self._output.write(prefix + ' ' + message + '\n')
self._output.flush()
def debug(self, message: str):
self.log('[Debug]', message)
def info(self, message: str):
self.log('[Info ]', message)
def warn(self, message: str):
self.log('[Warn ]', message)
def error(self, message: str):
self.log('[ERROR]', message)
def getOutput(self) -> Optional[IO]:
"""
:return: The output fileobject of this logger or None.
"""
return self._output
class Loggable(object):
def __init__(self, logger: Logger, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._logger = logger
def debug(self, message: str):
self._logger.debug(message)
def info(self, message: str):
self._logger.info(message)
def warn(self, message: str):
self._logger.warn(message)
def error(self, message: str):
self._logger.error(message)