Python使用logging模块的SMTPHandler发送告警日志邮件
Synopsis: 如果你想使用 Python 的内置模块 logging 中的 SMTPHandler 将出错时的日志,通过邮件的方式发送给管理员的话,可能你会遇到很多坑,本文将解决诸如 socket.timeout: timed out 和 smtplib.SMTPServerDisconnected: Connection unexpectedly closed: timed out 等错误,亲测有效
1. SMTPHandler
在 http://www.madmalls.com/blog/post/logging-for-python/#13-handler 中介绍了 Python 3 内置模块 logging
中的常用 Handler,如果我们既想将 logging.INFO
级别的日志保存到访问日志文件中,又想在应用出错时,将 logging.ERROR
及以上级别的日志通过邮件发送给管理员的话,就需要使用 logging.handlers.SMTPHandler()
了
2. 163邮箱非SSL(端口号25)
创建 test_smtphandler.py
import logging from logging.handlers import SMTPHandler import sys def main(): # 1. 创建 logger 实例 logger = logging.getLogger('test-smtphandler') # 2. 设置 logger 实例的日志级别,默认是 logging.WARNING logger.setLevel(logging.INFO) # 3. 创建 Handler # 注意 163 邮箱要求 fromaddr 和你发送邮件的邮箱(即你的邮箱账号)要一致 mail_handler = SMTPHandler( mailhost=('smtp.163.com', 25), fromaddr='xxx@163.com', toaddrs='接收报警邮件的地址', subject='[madmalls.com] 服务器出错了', credentials=('xxx@163.com', '客户端授权密码')) # 4. 单独设置 mail_handler 的日志级别为 ERROR mail_handler.setLevel(logging.ERROR) # 5. 将 Handler 添加到 logger 中 logger.addHandler(mail_handler) # 6. 应用的业务代码(故意出错) try: x = 1 / 0 except Exception: logger.error('[计算出错了] x = 1 / 0', exc_info=sys.exc_info()) if __name__ == '__main__': main()
2.1 开启 SMTP 服务
我将使用 stmp.163.com
的邮箱来发送邮件,首先你需要开通 SMTP
功能。访问 https://mail.163.com
,登录你的账号之后,依次单击 设置
、POP3/SMTP/IMAP
,开启 SMTP 服务,如下图所示:
然后,你在 Python 3 代码中想使用 163 邮箱来发送邮件的话,认证的用户名就是你的邮箱地址,但是密码不是你的登录密码,而是 客户端授权密码
,所以需要你先开启并生成这个密码,如下图所示:
注意:
163 邮箱的 SMTP 服务器地址为 smtp.163.com
,其中 非 SSL 协议端口号 为 25
, SSL 协议端口号 为 465/994
2.2 本地测试
运行此脚本:
$ python test_smtphandler.py
然后你应该就会收到一封包含应用程序出错信息的邮件:
2.3 腾讯云VPS测试
但是,如果你在腾讯云等 VPS 上运行时,由于它们的防火墙默认关闭了
25
号端口,所以你在执行脚本时会报错socket.timeout: timed out
$ python3 test-smtphandler.py --- Logging error --- Traceback (most recent call last): File "test-smtphandler.py", line 26, in main x = 1 / 0 ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/python-3.6/lib/python3.6/logging/handlers.py", line 1010, in emit smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout) File "/usr/local/python-3.6/lib/python3.6/smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "/usr/local/python-3.6/lib/python3.6/smtplib.py", line 336, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/local/python-3.6/lib/python3.6/smtplib.py", line 307, in _get_socket self.source_address) File "/usr/local/python-3.6/lib/python3.6/socket.py", line 724, in create_connection raise err File "/usr/local/python-3.6/lib/python3.6/socket.py", line 713, in create_connection sock.connect(sa) socket.timeout: timed out Call stack: File "test-smtphandler.py", line 32, in <module> main() File "test-smtphandler.py", line 28, in main logger.error('[计算出错了] x = 1 / 0', exc_info=sys.exc_info()) Message: '[计算出错了] x = 1 / 0' Arguments: ()
那么此时,你就只能使用 SSL 协议的 465
/994
端口号 了,但是你又会遇到问题,请接着看
3. 163邮箱SSL(端口号465/994)
查看 https://docs.python.org/3/library/logging.handlers.html#logging.handlers.SMTPHandler 文档,得知 logging.handlers.SMTPHandler
只支持 TLS 协议
,比如:
mail_handler = SMTPHandler(
分类: Python 技能进阶
标签: 日志 邮件 logging SMTPhandler
分享
相关推荐
作者

1 条评论
评论者的用户名
评论时间依西哈哈路
2019-12-02T09:53:11Z这个赚钱方式可以的,第一次见到