自动记录Flask消息到日志器

1 投票
1 回答
544 浏览
提问于 2025-04-18 10:00

我在看Flask的文档,学习如何设置日志记录。不过,我发现只有在我明确告诉它的时候,它才会写入日志(文档里也似乎是这么说的)。

这是我在create_app()里配置日志记录的方式:

def create_app(environment):
  """ creates the flask application. Uses a parameter to choose which config to use """
  app = Flask(__name__)
  # ...

  error_handler = RotatingFileHandler(
    os.path.join(app.config['LOG_FOLDER'], 'flask.log'),
    maxBytes=100000,
    backupCount=1
  )
  error_handler.setLevel(logging.NOTSET)
  error_handler.setFormatter(Formatter(
    '%(asctime)s %(levelname)s: %(message)s'
    '[in %(pathname)s:%(lineno)d]'
  ))
  app.logger.addHandler(error_handler)

现在我希望每当发生错误时,就像在调试器里那样,把错误的详细信息记录到日志里。这在生产环境中可以做到吗?

1 个回答

3

最简单的方法就是用 teardown_request 注册一个错误处理器:

@app.teardown_request
def log_errors(error):
    if error is None:
        return

    app.logger.error("An error occurred while handling the request", error)

撰写回答