Flask uses standard Python logging. All Flask-related messages are logged under the 'flask' logger namespace. Flask.loggerreturns the logger named 'flask.app', and can be used to log messages for your application.

@app.route('/login', methods=['POST'])
def login():
user = get_user(request.form['username']) if user.check_password(request.form['password']):
login_user(user)
app.logger.info('%s logged in successfully', user.username)
return redirect(url_for('index'))
else:
app.logger.info('%s failed to log in', user.username)
abort(401)

Basic Configuration

When you want to configure logging for your project, you should do it as soon as possible when the program starts. If app.logger is accessed before logging is configured, it will add a default handler. If possible, configure logging before creating the application object.

This example uses dictConfig() to create a logging configuration similar to Flask’s default, except for all logs:

from logging.config import dictConfig

dictConfig({
'version': 1,
'formatters': {'default': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
}},
'handlers': {'wsgi': {
'class': 'logging.StreamHandler',
'stream': 'ext://flask.logging.wsgi_errors_stream',
'formatter': 'default'
}},
'root': {
'level': 'INFO',
'handlers': ['wsgi']
}
}) app = Flask(__name__)

Default Configuration

If you do not configure logging yourself, Flask will add a StreamHandler to app.logger automatically. During requests, it will write to the stream specified by the WSGI server in environ['wsgi.errors'] (which is usually sys.stderr). Outside a request, it will log to sys.stderr.

Removing the Default Handler

If you configured logging after accessing app.logger, and need to remove the default handler, you can import and remove it:

from flask.logging import default_handler

app.logger.removeHandler(default_handler)

Email Errors to Admins

When running the application on a remote server for production, you probably won’t be looking at the log messages very often. The WSGI server will probably send log messages to a file, and you’ll only check that file if a user tells you something went wrong.

To be proactive about discovering and fixing bugs, you can configure a logging.handlers.SMTPHandler to send an email when errors and higher are logged.

import logging
from logging.handlers import SMTPHandler mail_handler = SMTPHandler(
mailhost='127.0.0.1',
fromaddr='server-error@example.com',
toaddrs=['admin@example.com'],
subject='Application Error'
)
mail_handler.setLevel(logging.ERROR)
mail_handler.setFormatter(logging.Formatter(
'[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
)) if not app.debug:
app.logger.addHandler(mail_handler)

This requires that you have an SMTP server set up on the same server. See the Python docs for more information about configuring the handler.

Injecting Request Information

Seeing more information about the request, such as the IP address, may help debugging some errors. You can subclass logging.Formatter to inject your own fields that can be used in messages. You can change the formatter for Flask’s default handler, the mail handler defined above, or any other handler.

from flask import request
from flask.logging import default_handler class RequestFormatter(logging.Formatter):
def format(self, record):
record.url = request.url
record.remote_addr = request.remote_addr
return super().format(record) formatter = RequestFormatter(
'[%(asctime)s] %(remote_addr)s requested %(url)s\n'
'%(levelname)s in %(module)s: %(message)s'
)
default_handler.setFormatter(formatter)
mail_handler.setFormatter(formatter)

Other Libraries

Other libraries may use logging extensively, and you want to see relevant messages from those logs too. The simplest way to do this is to add handlers to the root logger instead of only the app logger.

from flask.logging import default_handler

root = logging.getLogger()
root.addHandler(default_handler)
root.addHandler(mail_handler)

Depending on your project, it may be more useful to configure each logger you care about separately, instead of configuring only the root logger.

for logger in (
app.logger,
logging.getLogger('sqlalchemy'),
logging.getLogger('other_package'),
):
logger.addHandler(default_handler)
logger.addHandler(mail_handler)

Werkzeug

Werkzeug logs basic request/response information to the 'werkzeug' logger. If the root logger has no handlers configured, Werkzeug adds a StreamHandler to its logger.

Flask Extensions

Depending on the situation, an extension may choose to log to app.logger or its own named logger. Consult each extension’s documentation for details.

flask logger的更多相关文章

  1. flask 知识点总结

    ============================request对象的常用属性============================具体使用方法如下:request.headers, requ ...

  2. Python logging日志系统

    写我小小的日志系统 配置logging有以下几种方式: 1)使用Python代码显式的创建loggers, handlers和formatters并分别调用它们的配置函数: 2)创建一个日志配置文件, ...

  3. Flask 备注一(单元测试,Debugger, Logger)

    Flask 备注一(单元测试,Debugger, Logger) Flask是一个使用python开发Web程序的框架.依赖于Werkzeug提供完整的WSGI支持,以及Jinja2提供templat ...

  4. flask的自带logger和celery的自带logger的使用

    在celery和flask框架中都有自带的logger使用方法.下面记录一下相关的使用. flask中使用logger flask中的app对象FLASK()自带了logger方法,其调用的方式为: ...

  5. 【Flask】在Flask中使用logger

    https://blog.csdn.net/yannanxiu/article/details/53557657 Flask在0.3版本后就有了日志工具logger,在Flask的官方文档中这么记载: ...

  6. flask的日志输出current_app.logger.debug

    环境部署方式:nginx+supervisord+gunicorn在/etc/supervisord.conf中配置日志的输出路径stdout_logfile=/home/admin/workspac ...

  7. 如何在Flask的构架中传递logger给子模块

    Logger的传递 作为一个新手,如何将主函数的logger传入子模块是一件棘手的事情.某些情况下可以直接将logger作为参数传入子模块的构造函数中,但倘若子模块与主模块存在相互依赖的关系则容易出现 ...

  8. Flask备注二(Configurations, Signals)

    Flask备注二(Configuration, Signals) Flask是一个使用python开发Web程序的框架.依赖于Werkzeug提供完整的WSGI支持,以及Jinja2提供templat ...

  9. Flask微型框架入门笔记

    例程: from flask import Flask app = Flask(__name__) # 新建一个Flask可运行实体(名字参数如果是单独应用可以使用__name__变量,如果是modu ...

随机推荐

  1. css控制打印时只显示指定区域

      CreateTime--2017年9月26日08:16:04 Author:Marydon css控制打印时只显示指定区域 思路: 1.使用打印命令@media print: 2.控制执行打印命令 ...

  2. Solaris服务管理

    远程登录协议 telnet \ssh 等.当然我们可以查看谁登录过我的系统,以及可以利用ftp记录日志. 一.SMF: 服务管理工具 优点:自动恢复意外终止的服务,支持服务的依赖关系,一个服务可以有多 ...

  3. VS2010/12多核编译

    在工作中,我们的一个完整的项目肯定是由多个个解决方案组成的,我们在调试的时候就会不断的去编译修改过的解决方案,如果当修改的解决方案多了以后我们编译的速度就在很大的程度上决定了我们的工作效率.这时候我们 ...

  4. window 平台搭建简单的直播点播系统

    Windows平台如何搭建简单的直播系统前文已经有介绍,今天介绍下如何搭建简单的点播系统. 同样还是利用crtmpServer,crtmpServer可以从github中下载,可以从群里下载(群里有修 ...

  5. pandas-事例练习

    补充: DataFrame.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False) 功能:根据各标签的值中是否存在缺失数据 ...

  6. caffe搭建----Visual Studio 2015+CUDA8.0+CUDNN5配置Caffe-windows(BLVC)

    原文来源:  来源:Angle_Cal  2016-12-19 17:32 本博主修改于2017-09-12.  版权所有,转载请注明出处.   BLVC版本的Caffe-windows已经支持Vis ...

  7. RuntimeWarning: Parent module 'test_project.test_case' not found while handling absolute

    1.Pycharm2016.3.2,导入unittest框架后,运行脚本总是warming,但不影响脚本具体执行 2.通过网上查询,将"C:\Program Files\JetBrains\ ...

  8. 分享一个小工具:Excel表高速转换成JSON字符串

    在游戏项目中一般都须要由策划制作大量的游戏内容,当中非常大一部分是使用Excel表来制作的.于是程序就须要把Excel文件转换成程序方便读取的格式. 之前项目使用的Excel表导入工具都是通过Offi ...

  9. Visual Studio 2010无法启动调试

    现象:Visual Studio 2010点击调试或者按F5.Visual Studio 2010没有什么反应,但又不报错. 而点击运行不调试(Ctrl+F5)却没有问题. 解决的方法:打开项目属性, ...

  10. TCP 同步传输:客户端发送,服务器段接收

    1.服务器端程序 可以在TcpClient上调用GetStream()方法来获的链接到远程计算机的网络流NetworkStream.当在客户端调用时,他获的链接服务器端的流:当在服务器端调用时,他获得 ...