|
| 1 | +import contextlib |
| 2 | +import dataclasses |
| 3 | +import logging |
| 4 | +import logging.handlers |
| 5 | +import typing |
| 6 | + |
| 7 | +from lite_bootstrap.instruments.base import BaseInstrument |
| 8 | +from lite_bootstrap.service_config import ServiceConfig |
| 9 | +from lite_bootstrap.types import ApplicationT |
| 10 | + |
| 11 | + |
| 12 | +if typing.TYPE_CHECKING: |
| 13 | + from structlog.typing import EventDict, WrappedLogger |
| 14 | + |
| 15 | + |
| 16 | +with contextlib.suppress(ImportError): |
| 17 | + import structlog |
| 18 | + |
| 19 | + |
| 20 | +ScopeType = typing.MutableMapping[str, typing.Any] |
| 21 | + |
| 22 | + |
| 23 | +class AddressProtocol(typing.Protocol): |
| 24 | + host: str |
| 25 | + port: int |
| 26 | + |
| 27 | + |
| 28 | +class RequestProtocol(typing.Protocol): |
| 29 | + client: AddressProtocol |
| 30 | + scope: ScopeType |
| 31 | + method: str |
| 32 | + |
| 33 | + |
| 34 | +def tracer_injection(_: "WrappedLogger", __: str, event_dict: "EventDict") -> "EventDict": |
| 35 | + try: |
| 36 | + from opentelemetry import trace |
| 37 | + except ImportError: # pragma: no cover |
| 38 | + return event_dict |
| 39 | + |
| 40 | + event_dict["tracing"] = {} |
| 41 | + current_span = trace.get_current_span() |
| 42 | + if current_span == trace.INVALID_SPAN: |
| 43 | + return event_dict |
| 44 | + |
| 45 | + span_context = current_span.get_span_context() |
| 46 | + if span_context == trace.INVALID_SPAN_CONTEXT: # pragma: no cover |
| 47 | + return event_dict |
| 48 | + |
| 49 | + event_dict["tracing"]["trace_id"] = format(span_context.span_id, "016x") |
| 50 | + event_dict["tracing"]["span_id"] = format(span_context.trace_id, "032x") |
| 51 | + |
| 52 | + return event_dict |
| 53 | + |
| 54 | + |
| 55 | +DEFAULT_STRUCTLOG_PROCESSORS: typing.Final[list[typing.Any]] = [ |
| 56 | + structlog.stdlib.filter_by_level, |
| 57 | + structlog.stdlib.add_log_level, |
| 58 | + structlog.stdlib.add_logger_name, |
| 59 | + tracer_injection, |
| 60 | + structlog.stdlib.PositionalArgumentsFormatter(), |
| 61 | + structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S"), |
| 62 | + structlog.processors.StackInfoRenderer(), |
| 63 | + structlog.processors.format_exc_info, |
| 64 | + structlog.processors.UnicodeDecoder(), |
| 65 | +] |
| 66 | +DEFAULT_STRUCTLOG_FORMATTER_PROCESSOR: typing.Final = structlog.processors.JSONRenderer() |
| 67 | + |
| 68 | + |
| 69 | +class MemoryLoggerFactory(structlog.stdlib.LoggerFactory): |
| 70 | + def __init__( |
| 71 | + self, |
| 72 | + *args: typing.Any, # noqa: ANN401 |
| 73 | + logging_buffer_capacity: int, |
| 74 | + logging_flush_level: int, |
| 75 | + logging_log_level: int, |
| 76 | + log_stream: typing.Any = None, # noqa: ANN401 |
| 77 | + **kwargs: typing.Any, # noqa: ANN401 |
| 78 | + ) -> None: |
| 79 | + super().__init__(*args, **kwargs) |
| 80 | + self.logging_buffer_capacity = logging_buffer_capacity |
| 81 | + self.logging_flush_level = logging_flush_level |
| 82 | + self.logging_log_level = logging_log_level |
| 83 | + self.log_stream = log_stream |
| 84 | + |
| 85 | + def __call__(self, *args: typing.Any) -> logging.Logger: # noqa: ANN401 |
| 86 | + logger: typing.Final = super().__call__(*args) |
| 87 | + stream_handler: typing.Final = logging.StreamHandler(stream=self.log_stream) |
| 88 | + handler: typing.Final = logging.handlers.MemoryHandler( |
| 89 | + capacity=self.logging_buffer_capacity, |
| 90 | + flushLevel=self.logging_flush_level, |
| 91 | + target=stream_handler, |
| 92 | + ) |
| 93 | + logger.addHandler(handler) |
| 94 | + logger.setLevel(self.logging_log_level) |
| 95 | + logger.propagate = False |
| 96 | + return logger |
| 97 | + |
| 98 | + |
| 99 | +@dataclasses.dataclass(kw_only=True, slots=True, frozen=True) |
| 100 | +class LoggingInstrument(BaseInstrument): |
| 101 | + logging_log_level: int = logging.INFO |
| 102 | + logging_flush_level: int = logging.ERROR |
| 103 | + logging_buffer_capacity: int = 10 |
| 104 | + logging_extra_processors: list[typing.Any] = dataclasses.field(default_factory=list) |
| 105 | + logging_unset_handlers: list[str] = dataclasses.field( |
| 106 | + default_factory=list, |
| 107 | + ) |
| 108 | + |
| 109 | + def is_ready(self, service_config: ServiceConfig) -> bool: |
| 110 | + return not service_config.service_debug |
| 111 | + |
| 112 | + def bootstrap(self, _: ServiceConfig, __: ApplicationT | None = None) -> None: |
| 113 | + for unset_handlers_logger in self.logging_unset_handlers: |
| 114 | + logging.getLogger(unset_handlers_logger).handlers = [] |
| 115 | + |
| 116 | + structlog.configure( |
| 117 | + processors=[ |
| 118 | + *DEFAULT_STRUCTLOG_PROCESSORS, |
| 119 | + *self.logging_extra_processors, |
| 120 | + DEFAULT_STRUCTLOG_FORMATTER_PROCESSOR, |
| 121 | + ], |
| 122 | + context_class=dict, |
| 123 | + logger_factory=MemoryLoggerFactory( |
| 124 | + logging_buffer_capacity=self.logging_buffer_capacity, |
| 125 | + logging_flush_level=self.logging_flush_level, |
| 126 | + logging_log_level=self.logging_log_level, |
| 127 | + ), |
| 128 | + wrapper_class=structlog.stdlib.BoundLogger, |
| 129 | + cache_logger_on_first_use=True, |
| 130 | + ) |
| 131 | + |
| 132 | + def teardown(self, _: ApplicationT | None = None) -> None: |
| 133 | + structlog.reset_defaults() |
0 commit comments