Coverage for /usr/local/lib/python3.10/site-packages/opal_common-0.0.0-py3.10.egg/opal_common/logging_utils/thirdparty.py: 100%

8 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-10 11:54 +0000

1import logging 

2 

3 

4def hijack_uvicorn_logs(intercept_handler: logging.Handler): 

5 """Uvicorn loggers are configured to use special handlers. 

6 

7 Adding an intercept handler to the root logger manages to intercept logs from uvicorn, however, the log messages are duplicated. 

8 This is happening because uvicorn loggers are propagated by default - we get a log message once for the "uvicorn" / "uvicorn.error" 

9 logger and once for the root logger). Another stupid issue is that the "uvicorn.error" logger is not just for errors, which is confusing. 

10 

11 This method is doing 2 things for each uvicorn logger: 

12 1) remove all existing handlers and replace them with the intercept handler (i.e: will be logged via loguru) 

13 2) cancel propagation - which will mean messages will not propagate to the root logger (which also has an InterceptHandler), fixing the duplication 

14 """ 

15 # get loggers directly from uvicorn config - if they will change something - we will know. 

16 from uvicorn.config import LOGGING_CONFIG 

17 

18 uvicorn_logger_names = list(LOGGING_CONFIG.get("loggers", {}).keys()) or [ 

19 "uvicorn", 

20 "uvicorn.access", 

21 "uvicorn.error", 

22 ] 

23 for logger_name in uvicorn_logger_names: 

24 logger = logging.getLogger(logger_name) 

25 logger.handlers = [intercept_handler] 

26 logger.propagate = False