flask logger
Flask uses standard Python logging
. All Flask-related messages are logged under the 'flask'
logger namespace. Flask.logger
returns 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的更多相关文章
- flask 知识点总结
============================request对象的常用属性============================具体使用方法如下:request.headers, requ ...
- Python logging日志系统
写我小小的日志系统 配置logging有以下几种方式: 1)使用Python代码显式的创建loggers, handlers和formatters并分别调用它们的配置函数: 2)创建一个日志配置文件, ...
- Flask 备注一(单元测试,Debugger, Logger)
Flask 备注一(单元测试,Debugger, Logger) Flask是一个使用python开发Web程序的框架.依赖于Werkzeug提供完整的WSGI支持,以及Jinja2提供templat ...
- flask的自带logger和celery的自带logger的使用
在celery和flask框架中都有自带的logger使用方法.下面记录一下相关的使用. flask中使用logger flask中的app对象FLASK()自带了logger方法,其调用的方式为: ...
- 【Flask】在Flask中使用logger
https://blog.csdn.net/yannanxiu/article/details/53557657 Flask在0.3版本后就有了日志工具logger,在Flask的官方文档中这么记载: ...
- flask的日志输出current_app.logger.debug
环境部署方式:nginx+supervisord+gunicorn在/etc/supervisord.conf中配置日志的输出路径stdout_logfile=/home/admin/workspac ...
- 如何在Flask的构架中传递logger给子模块
Logger的传递 作为一个新手,如何将主函数的logger传入子模块是一件棘手的事情.某些情况下可以直接将logger作为参数传入子模块的构造函数中,但倘若子模块与主模块存在相互依赖的关系则容易出现 ...
- Flask备注二(Configurations, Signals)
Flask备注二(Configuration, Signals) Flask是一个使用python开发Web程序的框架.依赖于Werkzeug提供完整的WSGI支持,以及Jinja2提供templat ...
- Flask微型框架入门笔记
例程: from flask import Flask app = Flask(__name__) # 新建一个Flask可运行实体(名字参数如果是单独应用可以使用__name__变量,如果是modu ...
随机推荐
- 使用TypeDescriptor给类动态添加Attribute【转】
源文 : http://www.cnblogs.com/bicker/p/3326763.html 给类动态添加Attribute一直是我想要解决的问题,从msdn里找了很久,到Stack Overf ...
- Git经常使用命令
git --version 版本号号git help 帮助gitk 是个图形化的查看工具.gitk --all 所有分支历史-----------------------git pull 先拉git ...
- ListView 自己定义BaseAdapter实现单选打勾(无漏洞)
(假设须要完整demo,请评论留下邮箱) (眼下源代码已经不发送.假设须要源代码,加qq316701116.不喜勿扰) 近期由于一个项目的原因须要自己定义一个BaseAdapter实现ListVIew ...
- DataSource是什么
public interface DataSource 该工厂用于提供到此 DataSource 对象表示的物理数据源的连接.作为 DriverManager(二者区别:http://tobylxy. ...
- ffmpeg h264编码 extradata 为空
ffmpeg h264编码的例子前面的文章已经介绍,本来主要讲述影响AVCodecContext extradata是否为 空的配置项.如果要求open编码器以后AVCodecContext extr ...
- JavaScript插件编写指南
在编写插件之前,大家要先了解做插件的几个要点: 插件需要满足的条件 一个可复用的插件需要满足以下条件: 插件自身的作用域与用户当前的作用域相互独立,也就是插件内部的私有变量不能影响使用者的环境变量: ...
- 获取EF查询的SQL语句
在EF编程中我们能够通过lamda表达式能够进行查询数据.获取到IQueryable<T>结果,我们要想知道详细的SQL语句是什么须要使用ObjectQuery<T>进行处理 ...
- C语言关键字—-sizeof 、typedef、const、static、register、extern、#define
关键字:sizeof .#define.typedef.const.static.register.extern sizeof 1. 作用:求数据所占得内存空间大小 2. 本质:求数据得类型所占的内存 ...
- 03 svn 权限与用户管理
一:权限管理 (1)svn仓库各个作用 svnserve.conf [svn仓库的配置文件] password [svn仓库账号和密码配置文件] authz [svn仓库的访问权限] (2)访问权限 ...
- 实例具体解释:反编译Android APK,改动字节码后再回编译成APK
本文具体介绍了怎样反编译一个未被混淆过的Android APK,改动smali字节码后,再回编译成APK并更新签名,使之可正常安装.破译后的apk不管输入什么样的username和password都能 ...