flask日志处理

Posted in 2016-5-24 22:36 | Category: Python | Tags: flask python logging

使用文档上的一句话:

Applications fail, servers fail. Sooner or later you will see an exception in production. Even if your code is 100% correct, you will still see exceptions from time to time. Why? Because everything else involved will fail.

应用发生错误时发送邮件

这里文档上个人认为说的不清不楚,毕竟想要使用还要看logging的文档

原文档

ADMINS = ['yourname@example.com']
if not app.debug:
    import logging
    from logging.handlers import SMTPHandler
    mail_handler = SMTPHandler('127.0.0.1',
                               'server-error@example.com',
                               ADMINS, 'YourApplication Failed')
    mail_handler.setLevel(logging.ERROR)
    app.logger.addHandler(mail_handler)

实际上这里的好多参数没有交代清楚,具体可以看https://docs.python.org/2/library/logging.handlers.html#smtp-handler

具体代码

import logging
from logging.handlers import SMTPHandler
from logging import Formatter
config = app.config
credentials = (config['MAIL_USERNAME'], config['MAIL_PASSWORD'])
mail_handler = SMTPHandler(
    secure=(),
    mailhost=(config['MAIL_SERVER'], config['MAIL_PORT']),
    fromaddr='',
    toaddrs='',
    subject='YourApplication Failed',
    credentials=credentials)

mail_handler.setFormatter(Formatter …