【问题标题】:Logging Python SMTPHandler into emails for CLI SMTP Server将 Python SMTPHandler 记录到 CLI SMTP 服务器的电子邮件中
【发布时间】:2021-06-11 11:45:24
【问题描述】:

目标是完成一个 Flask 教程,其中使用 logging.handler.SMTPHandler 从 Python 将日志发送到 SMTP 调试服务器。

Python服务器在windows cli下运行,以管理员身份打开一个新的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.")

目前已尝试,调试服务器中没有出现任何消​​息:

什么可以是一个非常简单的例子可以做到这一点,否则使用调试文件也可以。 干杯。

【问题讨论】:

    标签: python smtp


    【解决方案1】:

    我认为您错过了将 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.")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      相关资源
      最近更新 更多