Skip to content

Commit 02f4faa

Browse files
committed
Do not use root logger
1 parent 3d3922c commit 02f4faa

File tree

5 files changed

+54
-43
lines changed

5 files changed

+54
-43
lines changed

src/galaxy/api/jsonrpc.py

+20-16
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@
88
from galaxy.reader import StreamLineReader
99
from galaxy.task_manager import TaskManager
1010

11+
12+
logger = logging.getLogger(__name__)
13+
14+
1115
class JsonRpcError(Exception):
1216
def __init__(self, code, message, data=None):
1317
self.code = code
@@ -133,7 +137,7 @@ async def send_request(self, method, params, sensitive_params):
133137
future = loop.create_future()
134138
self._requests_futures[self._last_request_id] = (future, sensitive_params)
135139

136-
logging.info(
140+
logger.info(
137141
"Sending request: id=%s, method=%s, params=%s",
138142
request_id, method, anonymise_sensitive_params(params, sensitive_params)
139143
)
@@ -151,7 +155,7 @@ def send_notification(self, method, params, sensitive_params=False):
151155
if False - no params are considered sensitive, if True - all params are considered sensitive
152156
"""
153157

154-
logging.info(
158+
logger.info(
155159
"Sending notification: method=%s, params=%s",
156160
method, anonymise_sensitive_params(params, sensitive_params)
157161
)
@@ -169,20 +173,20 @@ async def run(self):
169173
self._eof()
170174
continue
171175
data = data.strip()
172-
logging.debug("Received %d bytes of data", len(data))
176+
logger.debug("Received %d bytes of data", len(data))
173177
self._handle_input(data)
174178
await asyncio.sleep(0) # To not starve task queue
175179

176180
def close(self):
177181
if self._active:
178-
logging.info("Closing JSON-RPC server - not more messages will be read")
182+
logger.info("Closing JSON-RPC server - not more messages will be read")
179183
self._active = False
180184

181185
async def wait_closed(self):
182186
await self._task_manager.wait()
183187

184188
def _eof(self):
185-
logging.info("Received EOF")
189+
logger.info("Received EOF")
186190
self.close()
187191

188192
def _handle_input(self, data):
@@ -204,7 +208,7 @@ def _handle_response(self, response):
204208
request_future = self._requests_futures.get(int(response.id))
205209
if request_future is None:
206210
response_type = "response" if response.result is not None else "error"
207-
logging.warning("Received %s for unknown request: %s", response_type, response.id)
211+
logger.warning("Received %s for unknown request: %s", response_type, response.id)
208212
return
209213

210214
future, sensitive_params = request_future
@@ -225,7 +229,7 @@ def _handle_response(self, response):
225229
def _handle_notification(self, request):
226230
method = self._notifications.get(request.method)
227231
if not method:
228-
logging.error("Received unknown notification: %s", request.method)
232+
logger.error("Received unknown notification: %s", request.method)
229233
return
230234

231235
callback, signature, immediate, sensitive_params = method
@@ -242,12 +246,12 @@ def _handle_notification(self, request):
242246
try:
243247
self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method)
244248
except Exception:
245-
logging.exception("Unexpected exception raised in notification handler")
249+
logger.exception("Unexpected exception raised in notification handler")
246250

247251
def _handle_request(self, request):
248252
method = self._methods.get(request.method)
249253
if not method:
250-
logging.error("Received unknown request: %s", request.method)
254+
logger.error("Received unknown request: %s", request.method)
251255
self._send_error(request.id, MethodNotFound())
252256
return
253257

@@ -274,7 +278,7 @@ async def handle():
274278
except asyncio.CancelledError:
275279
self._send_error(request.id, Aborted())
276280
except Exception as e: #pylint: disable=broad-except
277-
logging.exception("Unexpected exception raised in plugin handler")
281+
logger.exception("Unexpected exception raised in plugin handler")
278282
self._send_error(request.id, UnknownError(str(e)))
279283

280284
self._task_manager.create_task(handle(), request.method)
@@ -305,10 +309,10 @@ async def send_task(data_):
305309
try:
306310
line = self._encoder.encode(data)
307311
data = (line + "\n").encode("utf-8")
308-
logging.debug("Sending %d byte of data", len(data))
312+
logger.debug("Sending %d byte of data", len(data))
309313
self._task_manager.create_task(send_task(data), "send")
310314
except TypeError as error:
311-
logging.error(str(error))
315+
logger.error(str(error))
312316

313317
def _send_response(self, request_id, result):
314318
response = {
@@ -348,18 +352,18 @@ def _send_notification(self, method, params):
348352
def _log_request(request, sensitive_params):
349353
params = anonymise_sensitive_params(request.params, sensitive_params)
350354
if request.id is not None:
351-
logging.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params)
355+
logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params)
352356
else:
353-
logging.info("Handling notification: method=%s, params=%s", request.method, params)
357+
logger.info("Handling notification: method=%s, params=%s", request.method, params)
354358

355359
@staticmethod
356360
def _log_response(response, sensitive_params):
357361
result = anonymise_sensitive_params(response.result, sensitive_params)
358-
logging.info("Handling response: id=%s, result=%s", response.id, result)
362+
logger.info("Handling response: id=%s, result=%s", response.id, result)
359363

360364
@staticmethod
361365
def _log_error(response, error, sensitive_params):
362366
data = anonymise_sensitive_params(error.data, sensitive_params)
363-
logging.info("Handling error: id=%s, code=%s, description=%s, data=%s",
367+
logger.info("Handling error: id=%s, code=%s, description=%s, data=%s",
364368
response.id, error.code, error.message, data
365369
)

src/galaxy/api/plugin.py

+22-20
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import dataclasses
33
import json
44
import logging
5-
import logging.handlers
65
import sys
76
from enum import Enum
87
from typing import Any, Dict, List, Optional, Set, Union
@@ -16,6 +15,9 @@
1615
from galaxy.task_manager import TaskManager
1716

1817

18+
logger = logging.getLogger(__name__)
19+
20+
1921
class JSONEncoder(json.JSONEncoder):
2022
def default(self, o): # pylint: disable=method-hidden
2123
if dataclasses.is_dataclass(o):
@@ -33,7 +35,7 @@ class Plugin:
3335
"""Use and override methods of this class to create a new platform integration."""
3436

3537
def __init__(self, platform, version, reader, writer, handshake_token):
36-
logging.info("Creating plugin for platform %s, version %s", platform.value, version)
38+
logger.info("Creating plugin for platform %s, version %s", platform.value, version)
3739
self._platform = platform
3840
self._version = version
3941

@@ -189,24 +191,24 @@ async def wrapper(*args, **kwargs):
189191
async def run(self):
190192
"""Plugin's main coroutine."""
191193
await self._connection.run()
192-
logging.debug("Plugin run loop finished")
194+
logger.debug("Plugin run loop finished")
193195

194196
def close(self) -> None:
195197
if not self._active:
196198
return
197199

198-
logging.info("Closing plugin")
200+
logger.info("Closing plugin")
199201
self._connection.close()
200202
self._external_task_manager.cancel()
201203
self._internal_task_manager.create_task(self.shutdown(), "shutdown")
202204
self._active = False
203205

204206
async def wait_closed(self) -> None:
205-
logging.debug("Waiting for plugin to close")
207+
logger.debug("Waiting for plugin to close")
206208
await self._external_task_manager.wait()
207209
await self._internal_task_manager.wait()
208210
await self._connection.wait_closed()
209-
logging.debug("Plugin closed")
211+
logger.debug("Plugin closed")
210212

211213
def create_task(self, coro, description):
212214
"""Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown"""
@@ -217,11 +219,11 @@ async def _pass_control(self):
217219
try:
218220
self.tick()
219221
except Exception:
220-
logging.exception("Unexpected exception raised in plugin tick")
222+
logger.exception("Unexpected exception raised in plugin tick")
221223
await asyncio.sleep(1)
222224

223225
async def _shutdown(self):
224-
logging.info("Shutting down")
226+
logger.info("Shutting down")
225227
self.close()
226228
await self._external_task_manager.wait()
227229
await self._internal_task_manager.wait()
@@ -238,7 +240,7 @@ def _initialize_cache(self, data: Dict):
238240
try:
239241
self.handshake_complete()
240242
except Exception:
241-
logging.exception("Unhandled exception during `handshake_complete` step")
243+
logger.exception("Unhandled exception during `handshake_complete` step")
242244
self._internal_task_manager.create_task(self._pass_control(), "tick")
243245

244246
@staticmethod
@@ -639,7 +641,7 @@ async def import_game_achievements(game_id, context_):
639641
except ApplicationError as error:
640642
self._game_achievements_import_failure(game_id, error)
641643
except Exception:
642-
logging.exception("Unexpected exception raised in import_game_achievements")
644+
logger.exception("Unexpected exception raised in import_game_achievements")
643645
self._game_achievements_import_failure(game_id, UnknownError())
644646

645647
async def import_games_achievements(game_ids_, context_):
@@ -803,7 +805,7 @@ async def import_game_time(game_id, context_):
803805
except ApplicationError as error:
804806
self._game_time_import_failure(game_id, error)
805807
except Exception:
806-
logging.exception("Unexpected exception raised in import_game_time")
808+
logger.exception("Unexpected exception raised in import_game_time")
807809
self._game_time_import_failure(game_id, UnknownError())
808810

809811
async def import_game_times(game_ids_, context_):
@@ -861,7 +863,7 @@ async def import_game_library_settings(game_id, context_):
861863
except ApplicationError as error:
862864
self._game_library_settings_import_failure(game_id, error)
863865
except Exception:
864-
logging.exception("Unexpected exception raised in import_game_library_settings")
866+
logger.exception("Unexpected exception raised in import_game_library_settings")
865867
self._game_library_settings_import_failure(game_id, UnknownError())
866868

867869
async def import_game_library_settings_set(game_ids_, context_):
@@ -919,7 +921,7 @@ async def import_os_compatibility(game_id, context_):
919921
except ApplicationError as error:
920922
self._os_compatibility_import_failure(game_id, error)
921923
except Exception:
922-
logging.exception("Unexpected exception raised in import_os_compatibility")
924+
logger.exception("Unexpected exception raised in import_os_compatibility")
923925
self._os_compatibility_import_failure(game_id, UnknownError())
924926

925927
async def import_os_compatibility_set(game_ids_, context_):
@@ -974,7 +976,7 @@ async def import_user_presence(user_id, context_) -> None:
974976
except ApplicationError as error:
975977
self._user_presence_import_failure(user_id, error)
976978
except Exception:
977-
logging.exception("Unexpected exception raised in import_user_presence")
979+
logger.exception("Unexpected exception raised in import_user_presence")
978980
self._user_presence_import_failure(user_id, UnknownError())
979981

980982
async def import_user_presence_set(user_ids_, context_) -> None:
@@ -1037,29 +1039,29 @@ def main():
10371039
main()
10381040
"""
10391041
if len(argv) < 3:
1040-
logging.critical("Not enough parameters, required: token, port")
1042+
logger.critical("Not enough parameters, required: token, port")
10411043
sys.exit(1)
10421044

10431045
token = argv[1]
10441046

10451047
try:
10461048
port = int(argv[2])
10471049
except ValueError:
1048-
logging.critical("Failed to parse port value: %s", argv[2])
1050+
logger.critical("Failed to parse port value: %s", argv[2])
10491051
sys.exit(2)
10501052

10511053
if not (1 <= port <= 65535):
1052-
logging.critical("Port value out of range (1, 65535)")
1054+
logger.critical("Port value out of range (1, 65535)")
10531055
sys.exit(3)
10541056

10551057
if not issubclass(plugin_class, Plugin):
1056-
logging.critical("plugin_class must be subclass of Plugin")
1058+
logger.critical("plugin_class must be subclass of Plugin")
10571059
sys.exit(4)
10581060

10591061
async def coroutine():
10601062
reader, writer = await asyncio.open_connection("127.0.0.1", port)
10611063
extra_info = writer.get_extra_info("sockname")
1062-
logging.info("Using local address: %s:%u", *extra_info)
1064+
logger.info("Using local address: %s:%u", *extra_info)
10631065
async with plugin_class(reader, writer, token) as plugin:
10641066
await plugin.run()
10651067

@@ -1069,5 +1071,5 @@ async def coroutine():
10691071

10701072
asyncio.run(coroutine())
10711073
except Exception:
1072-
logging.exception("Error while running plugin")
1074+
logger.exception("Error while running plugin")
10731075
sys.exit(5)

src/galaxy/http.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ async def _authorized_request(self, method, url, *args, **kwargs):
4444
)
4545

4646

47+
logger = logging.getLogger(__name__)
48+
4749
#: Default limit of the simultaneous connections for ssl connector.
4850
DEFAULT_LIMIT = 20
4951
#: Default timeout in seconds used for client session.
@@ -136,11 +138,11 @@ def handle_exception():
136138
if error.status >= 500:
137139
raise BackendError()
138140
if error.status >= 400:
139-
logging.warning(
141+
logger.warning(
140142
"Got status %d while performing %s request for %s",
141143
error.status, error.request_info.method, str(error.request_info.url)
142144
)
143145
raise UnknownError()
144146
except aiohttp.ClientError:
145-
logging.exception("Caught exception while performing request")
147+
logger.exception("Caught exception while performing request")
146148
raise UnknownError()

src/galaxy/proc_tools.py

-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
from typing import Iterable, NewType, Optional, List, cast
44

55

6-
76
ProcessId = NewType("ProcessId", int)
87

98

src/galaxy/task_manager.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33
from collections import OrderedDict
44
from itertools import count
55

6+
7+
logger = logging.getLogger(__name__)
8+
9+
610
class TaskManager:
711
def __init__(self, name):
812
self._name = name
@@ -15,23 +19,23 @@ def create_task(self, coro, description, handle_exceptions=True):
1519
async def task_wrapper(task_id):
1620
try:
1721
result = await coro
18-
logging.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description)
22+
logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description)
1923
return result
2024
except asyncio.CancelledError:
2125
if handle_exceptions:
22-
logging.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description)
26+
logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description)
2327
else:
2428
raise
2529
except Exception:
2630
if handle_exceptions:
27-
logging.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description)
31+
logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description)
2832
else:
2933
raise
3034
finally:
3135
del self._tasks[task_id]
3236

3337
task_id = next(self._task_counter)
34-
logging.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description)
38+
logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description)
3539
task = asyncio.create_task(task_wrapper(task_id))
3640
self._tasks[task_id] = task
3741
return task

0 commit comments

Comments
 (0)