import logging.config import sys from typing import Optional from owslib import context from owslib.dictutil import flatten from owslib.enums import Environment from owslib.logger.constants import LogFormat from owslib.logger.formatters import DDJsonFormatter, DebugFormatter class OwsStreamHandler(logging.StreamHandler): # type: ignore[type-arg] def __init__( self, environment: Environment, service_name: str, service_version: str, logger_name: Optional[str] = None, log_format: LogFormat = LogFormat.JSON, ) -> None: super().__init__(stream=sys.stdout) if log_format in [LogFormat.DEBUG, LogFormat.DEBUG_EXTRA]: self.formatter = DebugFormatter( debug_extra=log_format == LogFormat.DEBUG_EXTRA ) else: self.formatter = DDJsonFormatter( environment=environment, service_name=service_name, service_version=service_version, logger_name=logger_name, pretty=log_format == LogFormat.JSON_PRETTY, ) def emit(self, record: logging.LogRecord) -> None: if correlation_id := context.correlation_id.get(): setattr(record, "correlation_id", correlation_id) if request_context := context.request_context.get(): setattr( record, "request_context", flatten( request_context.dict( exclude_empty=True, exclude_keys=["authorization"], ) ), ) super().emit(record)