目标是完成一个Flask教程,其中使用logging.handler.SMTPHandler从Python向SMTP调试服务器发送日志。
Python服务器在windows cli下运行,以admin身份打开一个新的windows cli,然后运行:python -m smtpd -n -c DebuggingServer localhost:1025
要测试它,以下代码应该可以工作:
import logging
import sys
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
smtpHandler = logging.handlers.SMTPHandler(
mailhost = ("localhost",8025),
fromaddr = "alerts@localhost",
toaddrs = "geo555@localhost",
subject = "alert!"
)
smtpHandler.setLevel(logging.DEBUG)
logger.debug("here is the test logging for u.")
到目前为止已经尝试过,但调试服务器中没有出现任何消息:
- https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-error-handling不向调试服务器发送任何输出
- 如何使用python日志发送电子邮件';的SMTPHandler和SSL没有显式使用调试服务器,因此它不起作用
有一个非常简单的例子可以做到这一点,否则使用调试来归档也可以。干杯
我想您错过了将stmpHandler添加到记录器的机会:logger.addHandler(smtpHandler)
以下是完整的工作代码:
import logging
import logging.handlers
import sys
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
sender = "emailuser@localhost"
pwd = "pass123"
smtpHandler = logging.handlers.SMTPHandler(
mailhost=("localhost", 25),
fromaddr="noreply@example.com",
toaddrs="user@email.com",
subject="alert!",
credentials=(sender, pwd),
)
smtpHandler.setLevel(logging.DEBUG)
# add this line
logger.addHandler(smtpHandler)
logger.debug("here is the test logging for u.")