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的文档

原文档

1ADMINS = ['[email protected]']
2if not app.debug:
3    import logging
4    from logging.handlers import SMTPHandler
5    mail_handler = SMTPHandler('127.0.0.1',
6                               '[email protected]',
7                               ADMINS, 'YourApplication Failed')
8    mail_handler.setLevel(logging.ERROR)
9    app.logger.addHandler(mail_handler)

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

具体代码

 1import logging
 2from logging.handlers import SMTPHandler
 3from logging import Formatter
 4config = app.config
 5credentials = (config['MAIL_USERNAME'], config['MAIL_PASSWORD'])
 6mail_handler = SMTPHandler(
 7    secure=(),
 8    mailhost=(config['MAIL_SERVER'], config['MAIL_PORT']),
 9    fromaddr='',
10    toaddrs='',
11    subject='YourApplication Failed',
12    credentials=credentials)
13
14mail_handler.setFormatter(Formatter('''
15Message type:       %(levelname)s
16Location:           %(pathname)s:%(lineno)d
17Module:             %(module)s
18Function:           %(funcName)s
19Time:               %(asctime)s
20
21Message:
22
23%(message)s
24'''))
25mail_handler.setLevel(logging.ERROR)
26app.logger.addHandler(mail_handler)

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

1smtplib.SMTPServerDisconnected: Connection unexpectedly closed

记录应用错误到文件

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

1import logging
2from logging.handlers import RotatingFileHandler
3file_handler = RotatingFileHandler('python.log', maxBytes=1024 * 1024 * 100, backupCount=20)
4file_handler.setLevel(logging.ERROR)
5formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
6file_handler.setFormatter(formatter)
7app.logger.addHandler(file_handler)
作者: honmaple
链接: https://honmaple.me/articles/2016/05/flask日志处理.html
版权: CC BY-NC-SA 4.0 知识共享署名-非商业性使用-相同方式共享4.0国际许可协议
wechat
alipay

加载评论