python日志模块优缺点_flask.logger比更通用的python日志记录模块有什么优势?

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)

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.

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

解决方案

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

The logger exists so that Flask can log the internal workings of the module. 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.

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.

It's not an indication that you should use the logger yourself. Although it's valid to use it, you'd probably be better served by creating a separate logger for your own messages.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值