将FastAPI中的请求记录到项目目录中的特定文件中




我正在为FastAPI python上的字典构建一个API
我是这个框架的新手,但我有点喜欢它,所以我想试一试
作为需求的一部分,其中一个需求是将每个HTTP请求记录到我的项目中的特定文件.log文件中,而不是服务器端。
我试着使用中间件,但我想不通。。所以,如果你们对如何做到这一点有任何想法,请帮助我,因为我找不到太多关于这个话题的信息。

因此,在我的API enpoints(如mysite.com/words(中生成的每个请求,我都必须将其记录在一个文件中,包括时间戳和其他一些不重要的信息,因为这是细节的一部分,但我所希望的是能够获得每个请求并将其记录到一个文本文件中。。

提前谢谢。。

我在项目中使用了一个yaml配置文件,它看起来像这样记录uvicorn的所有内容:

version: 1
disable_existing_loggers: no
formatters:
simple:
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
handlers:
...
uvicorn:
class: logging.handlers.TimedRotatingFileHandler
level: DEBUG
formatter: simple
when: D
backupCount: 0
filename: ./logs/uvicorn.log
loggers:
...
uvicorn:
level: INFO
handlers: [uvicorn]
propagate: yes
qualname: uvicorn

您可以将其改编为代码,或者只在配置文件中使用

您可以简单地在Python中使用本机logging模块。例如:

#logger_config.py
import logging

def setup_logger(name) -> logging.Logger:
FORMAT = "[%(name)s %(module)s:%(lineno)s]nt %(message)s n"
TIME_FORMAT = "%d.%m.%Y %I:%M:%S %p"
logging.basicConfig(
format=FORMAT, datefmt=TIME_FORMAT, level=logging.DEBUG, filename="my-project-root/path/log-file-name.log"
)
logger = logging.getLogger(name)
return logger

# in any file that import fn setup_logger from the above 'logger_config.py', you can set up local logger like:
local_logger = setup_logger(__name__)
local_logger.info(
f"I am writing to file {FILENAME}. If that file did not exist, it would be automatically created. Here, you can change me to write about the call to a specific route function etc."
)

最新更新