如果您想使用自定义记录器(具有特定格式和日志级别),您应该注册处理程序。这里可以帮助你的例子app.py
:
import logging
from flask import Flask, current_app
app = Flask(__name__)
class MyFlaskExtension(object):
def __init__(self):
self.logger = logging.getLogger('my_flask_ext_logger')
self.logger.setLevel(logging.DEBUG)
# your custom handlers, formatters and filters here...
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
self.logger.addHandler(handler)
self.logger.info('My Was initialized')
def init_app(self, flask_app):
if not hasattr(flask_app, 'extensions'):
app.extensions = {}
app.extensions['MyFlaskExtension'] = self
app.config.setdefault('DEFAULT_PARAM_OF_YOUR_EXTENSION', None)
# other params
app.config.setdefault('ONE_MORE DEFAULT_PARAM...', 5)
@app.route('/')
def main():
# check your logger
my_extension_logger = current_app.extensions['MyFlaskExtension'].logger
my_extension_logger.info('Route "/". This is message from My extension logger')
return 'logger'
# init and register your extension
my_extension = MyFlaskExtension()
my_extension.init_app(app)
if __name__ == '__main__':
app.run()
运行我们的应用程序。您将在控制台中看到下一个输出:
INFO:my_flask_ext_logger:My Was initialized
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
现在让我们打开http://127.0.0.1:5000/
。您将看到来自记录器的消息:
INFO:my_flask_ext_logger:Route "/". This is message from My extension logger
127.0.0.1 - - [22/Aug/2017 16:28:53] "GET / HTTP/1.1" 200 -
希望这可以帮助。