flask日志处理


使用文档上的一句话:

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('''
Message type:       %(levelname)s
Location:           %(pathname)s:%(lineno)d
Module:             %(module)s
Function:           %(funcName)s
Time:               %(asctime)s

Message:

%(message)s
'''))
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)

其他方面不多说,这个多了一个 secure = () ,这是因为我的smtp服务需要使用TLS, 如果不加这行,会出现连接被拒绝的报错

smtplib.SMTPServerDisconnected: Connection unexpectedly closed

记录应用错误到文件

这个是google到的,参考资料
具体代码

import logging
from logging.handlers import RotatingFileHandler
file_handler = RotatingFileHandler('python.log', maxBytes=1024 * 1024 * 100, backupCount=20)
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
file_handler.setFormatter(formatter)
app.logger.addHandler(file_handler)