Adding python logging to FastApi endpoints, hosted on docker doesnt display API Endpoints logs

Adding python logging to FastApi endpoints, hosted on docker doesnt display API Endpoints logs

Inspired by @JPGs answer but using a pydantic model looked cleaner.

You might want to expose the more variables. This config worked good for me.


from pydantic import BaseModel

class LogConfig(BaseModel):
    Logging configuration to be set for the server

    LOGGER_NAME: str = mycoolapp
    LOG_FORMAT: str = %(levelprefix)s | %(asctime)s | %(message)s
    LOG_LEVEL: str = DEBUG

    # Logging config
    version = 1
    disable_existing_loggers = False
    formatters = {
        default: {
            (): uvicorn.logging.DefaultFormatter,
            fmt: LOG_FORMAT,
            datefmt: %Y-%m-%d %H:%M:%S,
        },
    }
    handlers = {
        default: {
            formatter: default,
            class: logging.StreamHandler,
            stream: ext://sys.stderr,
        },
    }
    loggers = {
        mycoolapp: {handlers: [default], level: LOG_LEVEL},
    }

Then import it into your main.py file as:

from logging.config import dictConfig
import logging
from .config import LogConfig

dictConfig(LogConfig().dict())
logger = logging.getLogger(mycoolapp)

logger.info(Dummy Info)
logger.error(Dummy Error)
logger.debug(Dummy Debug)
logger.warning(Dummy Warning)

Which gives:

enter

I would use dict log config

create a logger config as below,

# my_log_conf.py

log_config = {
    version: 1,
    disable_existing_loggers: False,
    formatters: {
        default: {
            (): uvicorn.logging.DefaultFormatter,
            fmt: %(levelprefix)s %(asctime)s %(message)s,
            datefmt: %Y-%m-%d %H:%M:%S,

        },
    },
    handlers: {
        default: {
            formatter: default,
            class: logging.StreamHandler,
            stream: ext://sys.stderr,
        },
    },
    loggers: {
        foo-logger: {handlers: [default], level: DEBUG},
    },
}

Then, load the config using dictConfig function as,

from logging.config import dictConfig
from fastapi import FastAPI

from some.where.my_log_conf import log_config

dictConfig(log_config)

app = FastAPI(debug=True)

Note: It is recommended to call the dictConfig(...) function before the FastAPI initialization.

After the initialization, you can use logger named foo-logger anywhere in your code as,

import logging

logger = logging.getLogger(foo-logger)

logger.debug(This is test)

Adding python logging to FastApi endpoints, hosted on docker doesnt display API Endpoints logs

Leave a Reply

Your email address will not be published. Required fields are marked *