-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathlogging.py
216 lines (167 loc) · 6.78 KB
/
logging.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
import asyncio
import logging
import sys
from copy import copy
from datetime import datetime
from logging import DEBUG, ERROR, FATAL, INFO, WARN, WARNING # noqa: F401
from threading import Lock, Thread
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Union
from grpclib.exceptions import StreamTerminatedError
import viam
if TYPE_CHECKING:
from .robot.client import RobotClient
LOG_LEVEL = INFO
LOGGERS: Dict[str, logging.Logger] = {}
_MODULE_PARENT: Optional["RobotClient"] = None
class _SingletonEventLoopThread:
_instance = None
_lock = Lock()
_ready_event = asyncio.Event()
_loop: Union[asyncio.AbstractEventLoop, None]
_thread: Thread
def __new__(cls):
# Ensure singleton precondition
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super(_SingletonEventLoopThread, cls).__new__(cls)
cls._instance._loop = None
cls._instance._thread = Thread(target=cls._instance._run)
cls._instance._thread.start()
return cls._instance
def _run(self):
self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
self._ready_event.set()
self._loop.run_forever()
def stop(self):
if self._loop is not None:
self._loop.call_soon_threadsafe(self._loop.stop)
self._thread.join()
def get_loop(self):
if self._loop is None:
raise RuntimeError("Event loop is None. Did you call .start() and .wait_until_ready()?")
return self._loop
async def wait_until_ready(self):
await self._ready_event.wait()
class _ModuleHandler(logging.Handler):
_parent: "RobotClient"
_logger: logging.Logger
_worker: _SingletonEventLoopThread
def __init__(self, parent: "RobotClient"):
super().__init__()
self._parent = parent
self._logger = logging.getLogger("ModuleLogger")
addHandlers(self._logger, True)
self._logger.setLevel(self.level)
self._worker = _SingletonEventLoopThread()
def setLevel(self, level: Union[int, str]) -> None:
self._logger.setLevel(level)
return super().setLevel(level)
async def handle_task_result(self, task: asyncio.Task):
try:
_ = task.result()
except (asyncio.CancelledError, asyncio.InvalidStateError, StreamTerminatedError):
pass
def emit(self, record: logging.LogRecord):
assert isinstance(record, logging.LogRecord)
# Fully qualified name of form "{subtype triplet}/{name}", e.g. "rdk:component:arm/myarm"
name = record.name.replace(".", "/")
message = f"{record.filename}:{record.lineno}\t{record.getMessage()}"
stack = f"exc_info: {record.exc_info}, exc_text: {record.exc_text}, stack_info: {record.stack_info}"
time = datetime.fromtimestamp(record.created)
try:
loop = self._worker.get_loop()
asyncio.run_coroutine_threadsafe(
self._asynchronously_emit(record, name, message, stack, time),
loop,
)
except Exception as err:
# If the module log fails, log using stdout/stderr handlers
self._logger.error(f"ModuleLogger failed for {record.name} - {err}")
self._logger.log(record.levelno, message)
async def _asynchronously_emit(self, record: logging.LogRecord, name: str, message: str, stack: str, time: datetime):
await self._worker.wait_until_ready()
task = self._worker.get_loop().create_task(
self._parent.log(name, record.levelname, time, message, stack),
name=f"{viam._TASK_PREFIX}-LOG-{record.created}",
)
task.add_done_callback(lambda t: asyncio.run_coroutine_threadsafe(self.handle_task_result(t), self._worker.get_loop()))
def close(self):
self._worker.stop()
super().close()
class _ColorFormatter(logging.Formatter):
MAPPING = {
"DEBUG": 37, # white
"INFO": 36, # cyan
"WARNING": 33, # yellow
"ERROR": 31, # red
"CRITICAL": 41, # white on red bg
}
def __init__(self, pattern):
logging.Formatter.__init__(self, pattern)
def format(self, record):
colored_record = copy(record)
levelname = colored_record.levelname
seq = self.MAPPING.get(levelname, 37) # default white
colored_levelname = f"\x1b[33;{seq}m{levelname}\x1b[0m"
colored_record.levelname = colored_levelname
return super().format(colored_record)
def getLogger(name: str) -> logging.Logger:
logger = LOGGERS.get(name)
if logger:
return logger
logger = logging.getLogger(name)
logger.setLevel(LOG_LEVEL)
addHandlers(logger)
LOGGERS[name] = logger
return logger
def addHandlers(logger: logging.Logger, use_default_handlers=False):
_addHandlers([logger], use_default_handlers)
def update_log_level(logger: logging.Logger, level: Union[int, str]):
if level == "":
level = LOG_LEVEL
logger.setLevel(level)
for handler in logger.handlers:
handler.setLevel(level)
def _addHandlers(loggers: Iterable[logging.Logger], use_default_handlers=False):
format = _ColorFormatter("%(asctime)s\t\t" + "%(levelname)s\t" + "%(name)s (%(filename)s:%(lineno)d)\t" + "%(message)s\t")
handlers: List[logging.Handler] = []
std_handler = logging.StreamHandler(stream=sys.stdout)
std_handler.setFormatter(format)
# filter out logs at error level or above
std_handler.setLevel(LOG_LEVEL)
std_handler.addFilter(filter=lambda record: (record.levelno < ERROR))
err_handler = logging.StreamHandler(stream=sys.stderr)
err_handler.setFormatter(format)
# filter out logs below error level
err_handler.setLevel(max(ERROR, LOG_LEVEL))
if _MODULE_PARENT is not None and not use_default_handlers:
mod_handler = _ModuleHandler(_MODULE_PARENT)
mod_handler.setFormatter(format)
mod_handler.setLevel(LOG_LEVEL)
handlers = [mod_handler]
else:
handlers = [std_handler, err_handler]
for logger in loggers:
logger.handlers.clear()
if "viam.sessions_client" in LOGGERS and LOGGERS["viam.sessions_client"] == logger:
logger.addHandler(std_handler)
logger.addHandler(err_handler)
else:
for h in handlers:
logger.addHandler(h)
def setParent(parent: "RobotClient"):
global _MODULE_PARENT
_MODULE_PARENT = parent
_addHandlers(LOGGERS.values())
def setLevel(level: int):
global LOG_LEVEL
LOG_LEVEL = level
for logger in LOGGERS.values():
logger.setLevel(LOG_LEVEL)
_addHandlers(LOGGERS.values())
def silence():
setLevel(FATAL + 1)
def shutdown():
logging.shutdown()