python - 如何用 flask 中的请求信息丰富日志消息?

标签 python logging flask

我有一个小的 Flask 应用程序,它像 REST API 一样使用,实现了很多这样的方法:

@route('/do/something', methods=['POST'])
def something():
    app.logger.debug("got request to /do/something")
    result = something_implementation(request.json())
    app.logger.debug("result was %s", str(result))
    return flask.Response(result)

我想使用来自请求对象的信息自动丰富这些日志消息,例如 header 信息、正文部分和任何其他方便的信息。

我如何以一种优雅的 Pythonic 方式做到这一点?

当然,我可以将 app.logger 包装在我自己的函数中,并传递请求对象和消息,但我缺少一种更好、更简单的方法。

最佳答案

我通常在我的 app.py 文件中包含类似这样的内容来记录每个请求的调试信息,以及处理标准错误:

# Useful debugging interceptor to log all values posted to the endpoint
@app.before_request
def before():
    values = 'values: '
    if len(request.values) == 0:
        values += '(None)'
    for key in request.values:
        values += key + ': ' + request.values[key] + ', '
    app.logger.debug(values)

# Useful debugging interceptor to log all endpoint responses
@app.after_request
def after(response):
    app.logger.debug('response: ' + response.status + ', ' + response.data.decode('utf-8'))
    return response

# Default handler for uncaught exceptions in the app
@app.errorhandler(500)
def internal_error(exception):
    app.logger.error(exception)
    return flask.make_response('server error', 500)

# Default handler for all bad requests sent to the app
@app.errorhandler(400)
def handle_bad_request(e):
    app.logger.info('Bad request', e)
    return flask.make_response('bad request', 400)v

关于python - 如何用 flask 中的请求信息丰富日志消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39727163/

相关文章:

python - 无法用 flask 设置 cookie

python - 如果有正向前瞻和正向后向但没有定界符,我该如何拆分字符串?

python - 如何在 Jupyter Notebook 中禁用单元格截断?

tomcat - 为在 tomcat 中运行的 grails 应用程序动态重新加载 log4j.properties

python - 在 python 2.6 中加载具有变量路径的模块?

java - 使用方面记录 java 中方法的进入、退出和异常

python - 动态调整日志格式

python - 使用 PyCharm 调试器运行 Flask CLI 命令

jquery - 在python flask中获取jquery post数据null

python - flask 与应用程序混淆