使用Flask转储HTTP请求

Mik*_*maa 9 python flask

我正在开发基于Flask应用程序的Web应用程序(https://github.com/opensourcehacker/sevabot),它具有基于HTTP的API服务.

许多开发人员正在使用和扩展API,我想添加一个功能,将Flask的HTTP请求打印到Python日志输出,这样您就可以看到原始HTTP有效负载,源IP和头文件.

  • Flask提供了什么钩子,这种HTTP请求转储最容易实现

  • 是否有任何现有的解决方案和最佳实践可供学习?

Daz*_*all 10

Flask 在at处提供了一个标准记录器current_app.logger,这个gist中有一个示例配置,但是如果要记录每个请求,可以在before_request处理程序中集中日志记录调用:

from flask import request, current_app

@app.before_request
def log_request():
    if current_app.config.get('LOG_REQUESTS'):
        current_app.logger.debug('whatever')
        # Or if you dont want to use a logger, implement
        # whatever system you prefer here
        # print request.headers
        # open(current_app.config['REQUEST_LOG_FILE'], 'w').write('...')
Run Code Online (Sandbox Code Playgroud)

  • 使用以下命令初始化:logHandler = RotatingFileHandler(log_path,maxBytes = 10000,backupCount = 1)formatter = logging.Formatter('[%(asctime)s] {%(pathname)s - %(levelname)s - %(filename)s - %(模块)s - %(funcName)s - %(消息)s')logHandler.setFormatter(格式化程序)app.logger.addHandler(logHandler)app.logger.setLevel(logging.INFO)然后你可以调用app.logger .info("消息或字符串") (3认同)