From a9ae33c4b9dbe566d2ada07affb8b5a135f9b6eb Mon Sep 17 00:00:00 2001 From: Egor Tensin Date: Thu, 28 Dec 2023 01:00:45 +0100 Subject: test/py/ -> test/src/ --- test/src/lib/logging.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 test/src/lib/logging.py (limited to 'test/src/lib/logging.py') diff --git a/test/src/lib/logging.py b/test/src/lib/logging.py new file mode 100644 index 0000000..663eb3a --- /dev/null +++ b/test/src/lib/logging.py @@ -0,0 +1,45 @@ +# Copyright (c) 2023 Egor Tensin +# This file is part of the "cimple" project. +# For details, see https://github.com/egor-tensin/cimple. +# Distributed under the MIT License. + +from contextlib import contextmanager +import logging +import logging.config +import logging.handlers +import multiprocessing as mp + + +@contextmanager +def child_logging_thread(): + # Delegating logging to the parent logger. + ctx = mp.get_context('spawn') + queue = ctx.Queue() + listener = logging.handlers.QueueListener(queue, logging.getLogger()) + listener.start() + try: + yield queue + finally: + listener.stop() + + +@contextmanager +def configure_logging_in_child(queue): + config = { + 'version': 1, + 'handlers': { + 'sink': { + 'class': 'logging.handlers.QueueHandler', + 'queue': queue, + }, + }, + 'root': { + 'handlers': ['sink'], + 'level': 'DEBUG', + }, + } + logging.config.dictConfig(config) + try: + yield + except Exception as e: + logging.exception(e) -- cgit v1.2.3