与更通用的 python 日志记录模块相比,flask.logger 有什么优势? [英] What is the advantage of flask.logger over the more generic python logging module?

查看:17
本文介绍了与更通用的 python 日志记录模块相比,flask.logger 有什么优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Flask 构建一个网站,我现在正在为它添加一些日志记录,我发现了 这些文档.基本示例如下:

I'm building a website using Flask and I'm now in the process of adding some logging to it for which I found these docs. The basic example is as follows:

if not app.debug:
    import logging
    from themodule import TheHandlerYouWant
    file_handler = TheHandlerYouWant(...)
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

之后您可以使用app.logger.error('An error发生')进行记录.这工作正常,但除了我没有看到比常规 python 日志记录模块有任何优势的事实之外,我还看到了一个主要的缺点:如果我想在请求上下文之外进行日志记录(例如,当使用 cron 作业运行一些代码时) 我收到错误,因为我在请求上下文之外使用了应用程序.

after which you can log using app.logger.error('An error occurred'). This works fine, but apart from the fact that I do not see any advantage over the regular python logging module I also see a major downside: if I want to log outside of a request context (when for example running some code with a cron job) I get errors because I'm using app outside of the request context.

所以我的主要问题;我为什么要使用 Flask 记录器?它建起来的原因是什么?

So my main question; why would I use the Flask logger at all? What is the reason that it was ever built?

推荐答案

Flask 记录器使用通用"Python 日志记录,它是一个 logging.getLogger(name) 和其他任何一样.

The Flask logger uses the "generic" Python logging, it's a logging.getLogger(name) like any other.

记录器的存在是为了让 Flask 应用程序和视图可以记录在执行过程中发生的事情.例如,它会在调试模式下记录 500 个错误的回溯.配置示例展示了如何在未处于调试模式时启用这些在生产中仍然有用的日志.

The logger exists so that Flask app and views can log things that happen during execution. For example, it will log tracebacks on 500 errors during debug mode. The configuration example is there to show how to enable these logs, which are still useful in production, when you are not in debug mode.

拥有内部记录器并不是 Flask 所独有的,它是在 Python 中使用日志记录的标准方式.每个模块都定义了自己的记录器,但日志记录的配置仅由链中的最后一个链接处理:您的项目.

Having an internal logger is not unique to Flask, it's the standard way to use logging in Python. Every module defines it's own logger, but the configuration of the logging is only handled by the last link in the chain: your project.

您也可以将 app.logger 用于您自己的消息,尽管这不是必需的.您还可以为自己的消息创建一个单独的记录器.最后,都是 Python 日志记录.

You can also use app.logger for your own messages, although it's not required. You could also create a separate logger for your own messages. In the end, it's all Python logging.

这篇关于与更通用的 python 日志记录模块相比,flask.logger 有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆