背景
记录日志,在任何项目中,都是很重要的。在Flask项目中,即有Flask提供的logger可以用来记录log,也可以通过直接使用Python的logging模块自定义logger来记录。那么这两者是什么关系,又该怎么使用呢?
思路
Python的logging模块
先看下对于logging模块的官方介绍
Loggers have the following attributes and methods. Note that Loggers are never instantiated directly, but always through the module-level function logging.getLogger(name). Multiple calls to getLogger() with the same name will always return a reference to the same Logger object.
The name is potentially a period-separated hierarchical value, like foo.bar.baz (though it could also be just plain foo, for example). Loggers that are further down in the hierarchical list are children of loggers higher up in the list. For example, given a logger with a name of foo, loggers with names of foo.bar, foo.bar.baz, and foo.bam are all descendants of foo. The logger name hierarchy is analogous to the Python package hierarchy, and identical to it if you organise your loggers on a per-module basis using the recommended construction logging.getLogger(__name__). That’s because in a module, __name__ is the module’s name in the Python package namespace.
上面主要告诉我们三点,
可以通过logging.getLogger(name)来获取一个logger,相同名字的logger,其实是同一个logger。
logger是通过name进行继承的,比如foo.bar就是foo 的子logger。就可以是实现我们通过配置一个rootLogger,然后直接使用rootLogger.sublogger来记录一下内容,而不需要单独再配置一遍。
当使用logging.getLogger(__name__)时,__name__就是这个模块所在的python package的namespace。
flask提供的logger
再看下flask中的logging模块:
Flask uses standard Python logging. All Flask-related messages are logged under the 'flask&