|
2 | 2 | from typing import List |
3 | 3 |
|
4 | 4 | import structlog |
| 5 | +from opentelemetry.sdk._logs import LoggingHandler |
5 | 6 | from structlog.typing import Processor |
6 | 7 |
|
7 | 8 | from ..config import AppConfig |
|
14 | 15 |
|
15 | 16 | def init_logger(config: AppConfig) -> None: |
16 | 17 | """ |
17 | | - Configure structlog and stdlib logging with shared handler and formatter. |
| 18 | + Function to initialize logging configuration using `structlog` and Python's standard |
| 19 | + logging module. It supports dynamic log level adjustment, shared processors for |
| 20 | + structlog and standard loggers, and tailored configurations for different environments |
| 21 | + (local, test, or production). Ensures consistent formatting across application logs |
| 22 | + and integrates handlers for OpenTelemetry logs if present. |
| 23 | +
|
| 24 | + Args: |
| 25 | + config (AppConfig): Configuration object containing application-wide settings |
| 26 | + such as DEBUG flag and environment status. |
| 27 | +
|
| 28 | + Raises: |
| 29 | + None |
| 30 | +
|
| 31 | + Returns: |
| 32 | + None |
18 | 33 |
|
19 | | - :param config: The app configuration |
20 | | - :type config: AppConfig |
21 | | - :return: |
22 | 34 | """ |
23 | 35 | # Strongly inspired by https://gist.github.com/nymous/f138c7f06062b7c43c060bf03759c29e |
24 | 36 |
|
@@ -76,9 +88,17 @@ def init_logger(config: AppConfig) -> None: |
76 | 88 | ) |
77 | 89 | ) |
78 | 90 |
|
79 | | - # Use structlog to format logs coming from stdlib logger |
| 91 | + # Get root logger |
80 | 92 | stdlib_logger = logging.getLogger() |
81 | | - stdlib_logger.handlers.clear() |
| 93 | + |
| 94 | + # In case there's a OTEL handler we keep it but remove all the others, |
| 95 | + # in case this function is called multiple times. |
| 96 | + # NOTE all the processors are not applied to OTEL logs! |
| 97 | + for handler in stdlib_logger.handlers: |
| 98 | + if not isinstance(handler, LoggingHandler): |
| 99 | + stdlib_logger.removeHandler(handler) |
| 100 | + |
| 101 | + # Use structlog to format logs coming from stdlib logger |
82 | 102 | stdlib_logger.addHandler(stdlib_handler) |
83 | 103 | stdlib_logger.setLevel(log_level) |
84 | 104 |
|
|
0 commit comments