向 FastApi 端点添加 python 日志记录,托管在 docker 上不会显示 API 端点日志

问题描述 投票:0回答:2

我有一个 fastapi 应用程序,我想在其中添加 python 日志记录。我按照基本教程添加了这个,但这并没有添加API,而只是添加了gunicorn日志记录。

所以我有一个使用 docker build 托管的本地服务器,因此使用

docker-compose up
运行服务器并使用 api 客户端测试我的端点(Insomnia,类似于邮递员)。 下面的代码没有创建日志文件,因此没有添加日志语句。

我的项目str如下:

project/
  src/ 
    api/
      models/ 
        users.py
      routers/
        users.py
      main.py
      logging.conf
"""
main.py Main is the starting point for the app.
"""
import logging
import logging.config
from fastapi import FastAPI
from msgpack_asgi import MessagePackMiddleware
import uvicorn

from api.routers import users


logger = logging.getLogger(__name__)


app = FastAPI(debug=True)
app.include_router(users.router)


@app.get("/check")
async def check():
    """Simple health check endpoint."""
    logger.info("logging from the root logger")
    return {"success": True}


另外,我正在使用

gunicorn.conf
,看起来像这样:

[program:gunicorn]
command=poetry run gunicorn -c /etc/gunicorn/gunicorn.conf.py foodgame_api.main:app
directory=/var/www/
autostart=true
autorestart=true
redirect_stderr=true

gunicorn.conf.py
作为

import multiprocessing
bind = "unix:/tmp/gunicorn.sock"
workers = multiprocessing.cpu_count() * 2 + 1
worker_class = "uvicorn.workers.UvicornWorker"
loglevel = "debug"
errorlog = "-"
capture_output = True
chdir = "/var/www"
reload = True
reload_engine = "auto"
accesslog = "-"
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'

这是我在 docker 上上述 API 端点的输出终端:

有人可以指导我吗?我是 FastApi 的新手,因此我们将不胜感激。

python-3.x logging docker-compose gunicorn fastapi
2个回答
60
投票

受到JPG的回答的启发,但使用pydantic模型看起来更干净。

您可能想暴露更多变量。这个配置对我来说效果很好。

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 = {
        LOGGER_NAME: {"handlers": ["default"], "level": LOG_LEVEL},
    }

然后将其导入到您的

main.py
文件中:

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")

这给出了:


20
投票

我会使用dict日志配置

创建一个记录器配置如下,

# 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"},
    },
}

然后,使用

dictConfig
函数加载配置,

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)

注意: 建议在

dictConfig(...)
初始化之前调用
FastAPI
函数。

初始化后,您可以在代码中的任何位置使用名为

foo-logger
的记录器,

import logging

logger = logging.getLogger('foo-logger')

logger.debug('This is test')
© www.soinside.com 2019 - 2024. All rights reserved.