[Python] FastAPI Azure Opentelemetry logger does not map LogLevels correctly

Discussão em 'Python' iniciado por Stack, Dezembro 8, 2024.

  1. Stack

    Stack Membro Participativo

    Logs of my FastAPI app are currently written into AppServiceConsoleLogs table in Log Analytics, Azure. I initialize my loggers with (where LOGGING_CONFIG is just the logging config as Class):

    class ApiLoggerConfig(BaseModel):
    """Logging configuration to be set for all APIs."""

    formatters: dict = {
    "uvicorn": {
    "()": "uvicorn.logging.DefaultFormatter",
    "fmt": "%(levelprefix)s %(asctime)s %(name)s:%(lineno)d: %(message)s",
    "datefmt": DATEFMT,
    },
    "access": {
    "()": "uvicorn.logging.AccessFormatter",
    "fmt": '%(levelprefix)s %(asctime)s %(name)s: %(client_addr)s - "%(request_line)s" %(status_code)s',
    "datefmt": DATEFMT,
    },
    }

    handlers: dict = {
    "uvicorn": {
    "formatter": "uvicorn",
    "class": "logging.StreamHandler",
    "stream": "ext://sys.stderr",
    },
    "access": {
    "formatter": "access",
    "class": "logging.StreamHandler",
    "stream": "ext://sys.stdout",
    },
    }

    loggers: dict = {
    "uvicorn": {"handlers": ["uvicorn"], "level": LOG_LEVEL, "propagate": False},
    "uvicorn.error": {"level": LOG_LEVEL},
    "uvicorn.access": {
    "handlers": ["access"],
    "level": LOG_LEVEL,
    "propagate": False,
    },
    }
    def add_logger(
    self,
    name: str,
    handler: str = "default",
    propagate: bool = False,
    ):

    self.loggers[name] = {
    "handlers": [handler],
    "level": self.LOG_LEVEL,
    "propagate": propagate,
    }


    def _setup_logging(app: FastAPI):
    LOGGING_CONFIG = ApiLoggerConfig()
    # Load Azure logging config for cloud setup only
    if os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING"):
    from azure.monitor.opentelemetry import configure_azure_monitor
    from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor

    # set metrics extractor to root
    configure_azure_monitor()
    FastAPIInstrumentor.instrument_app(app)
    LOGGING_CONFIG.add_logger(__name__)
    dictConfig(LOGGING_CONFIG)
    return logging.getLogger(__name__)


    app = FastAPI()

    logger = _setup_logging(app)

    @app.get("/", response_model=HealthResponse)
    async def health() -> Dict[str, str]:
    """Simple heath check endpoint.

    Returns:
    The response follows the provided HealthResponse schema.
    """
    logger.info("I am healthy")
    return {"message": "API running."}



    However, INFO logs get associated with the LogLevel ERROR ( especially for all logs of the __name__ logger). The setup works locally without any issues.

    [​IMG]

    What am I doing wrong?

    Continue reading...

Compartilhe esta Página