flask logger

摘要:
flask具有标准的Python日志记录。所有flask相关的消息都记录在“flask”日志文件名空间中。flask日志文件返回名为“flask的日志文件。应用程序',andcanbeusedtologmessagesforyourapplication.@app.route('/log

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
'
    '%(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》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇c语言-----劫持系统03【DB宝46】NoSQL数据库之CouchBase简介、集群搭建、XDCR同步及备份恢复下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Android Handler与多线程

本文首先解释一下handler是用来干嘛的,然后通过例子介绍其在多线程中的应用。 什么是Handler      handler通俗一点讲就是用来在各个进程之间发送数据的处理对象。在任何进程中,只要获得了另一个进程的handler则可以通过 handler.sendMessage(message)方法向那个进程发送数据。基于这个机制,我们在处理多线程的时...

netty中的引导Bootstrap服务端

引导一个应用程序是指对它进行配置,并使它运行起来的过程。 一、Bootstrap 类 引导类的层次结构包括一个抽象的父类和两个具体的引导子类,如图 8-1 所示 服务器致力于使用一个父 Channel 来接受来自客户端的连接,并创建子 Channel 以用于它们之间的通信; 而客户端将最可能只需要一个单独的、没有父Channel 的Channel 来用...

flask 使用Flask-SQLAlchemy管理数据库(连接数据库服务器、定义数据库模型、创建库和表) --

使用Flask-SQLAlchemy管理数据库 扩展Flask-SQLAlchemy集成了SQLAlchemy,它简化了连接数据库服务器、管理数据库操作会话等各种工作,让Flask中的数据处理体验变得更轻松。首先使用pipenv安装Flask-SQLAlchemy以及其依赖(主要是SQLAlchemy): pipenv install flask-sqla...

python处理xml大文件[xml.sax]

博客已迁移, 新地址 ===================== 之前使用过python使用dom读取简单配置xml文件的http://blog.csdn.net/wklken/article/details/7270117 今天遇到大文件处理,使用dom占用资源太多,改用sax处理 dom和sax区别可以自己google下 需求:读取xml数据文件,文...

Android 聊天室(一)

         为了提高自己在Android开发上的能力,博主决定写一个类似于QQ、微信的聊天软件。不过,简单的想想之后发现,要实现这样的一个聊天软件,需要学习和掌握的东西还很多。作为一个Android开发的小白,也没有足够的实力能很快对这个APP的开发有很大的突破。          于是,博主参考《疯狂Android讲义》中关于“Android网络...

3步把您的java程序转换为webservice

1、选择要转换的java文件,生成class2、写wsdd3、发布剩下的就只有调用了wsdl2java我原来的系统是CICS的,对后台封装了一层,现在用webservice再封装一层,前台页面,控制,数据传输,数据处理统统都可以分开了,爽//以下是从网上找的关于AXIS的入门教程一、Axis安装 1、环境 J2SE SDK 1.3 or 1.4: 我使用...