Python Flask 通过所有模块记录请求正文

标签 python logging flask

我正在尝试记录传入的发布请求的请求正文,并将其保留在此后函数中调用的所有模块中。 这是我想要实现的目标的示例:

main_app.py

from flask import Flask
from other_file import other_module
import logging

FORMAT = '%(request_body_id)s- %(message)s'
logging.basicConfig(format=FORMAT)
log = logging.getLogger('test_logger')
@app.route('/', methods=['POST'])
def test_function():
   log = logging.LoggerAdapter(log, {'request_body_id': request.body['id']})
   log.info("My message")
   other_module()
   return "foo"

other_file.py

log = logging.getLogger('test_logger')
def other_module():
   log.info("My second message")

我正在寻找的是:

>>> INFO 123456- My message
>>> INFO 123456- My second message

我得到的是:

>>> INFO 123456- My message
>>> INFO - My second message

更新: 将请求正文作为参数传递给 other_module 不是一种选择,因为在实际情况下有大量模块被调用,需要输出请求源。

最佳答案

您可以使用 logging.Formatter 将任何其他数据添加到日志中。只是一个例子:

log.py

import logging
from flask import request


class __RequestFormatter(logging.Formatter):

    def format(self, record):
        # you can set here everything what you need
        # I just added url and id from GET parameter
        record.id = request.args.get('id')
        record.url = request.url
        return super().format(record)

# format of our log record.
# print url and id of record which was set in format()
__stream_handler = logging.StreamHandler()
__stream_handler.setFormatter(__RequestFormatter(
    '[%(asctime)s %(levelname)s] requested: %(url)s, id: %(id)s in %(module)s: %(message)s'
))

logger = logging.getLogger('my_loger')
logger.setLevel(logging.INFO)
logger.addHandler(__stream_handler)

app.py

from flask import Flask

from log import logger
from other_file import other_module

app = Flask(__name__)


@app.route('/test')
def test():
    logger.info('/test was called')
    other_module()
    return 'hi'

other_file.py

from log import logger


def other_module():
   logger.info("My second message")

现在让我们调用 /test?id=example_id/test?id=example_id2 并检查日志:

[2018-09-28 17:40:48,669 INFO] requested: http://127.0.0.1:5000/test?id=example_id, id: example_id in app: /test was called
[2018-09-28 17:40:48,670 INFO] requested: http://127.0.0.1:5000/test?id=example_id, id: example_id in other_file: My second message

[2018-09-28 17:40:51,475 INFO] requested: http://127.0.0.1:5000/test?id=example_id2, id: example_id2 in app: /test was called
[2018-09-28 17:40:51,476 INFO] requested: http://127.0.0.1:5000/test?id=example_id2, id: example_id2 in other_file: My second message

正如您所看到的,所有消息都包含请求的id。因此,您可以使用Formatter来自定义您需要的一切。您也可以尝试使用 flask-log-request-id .

希望这有帮助。

关于Python Flask 通过所有模块记录请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52413158/

相关文章:

python - 我如何确定 python 使用的类型的确切大小

python - 如何将大量分类数据从字符串自动转换为数值?

python - python 中离散傅立叶变换 (FT) 的教程、技巧和香蕉皮

php - 在 monolog 中设置 json 格式化程序

Python:如何传递对函数的引用

c# - Serilog 未记录到 SQL Server

logging - 是否有开源工具可以自动查找日志文件中的模式?

python - 如何返回多个模型/表 flask-sqlalchemy?

python - Flask/Heroku/Redis/RQ 内部服务器错误

python - 是否可以使用 flask 模板在网格/表格中显示产品?