Python日志记录模块不发送电子邮件

时间:2014-09-13 12:05:44

标签: logging python-3.x smtp

我正在尝试将我的网络应用程序错误/例外记录到文件和电子邮件中。记录到文件有效,但不发送电子邮件。 Python版本是3.4。

代码:

# Filename: my_app/log.py

import logging
import logging.handlers
from . import config

LOG_FILENAME = '{}/logs/app.log'.format(config.module_path)

# Logger and it's output level
app_logger = logging.getLogger('my_app')
app_logger.setLevel(logging.DEBUG)

# File handler
file_handler = logging.handlers.RotatingFileHandler(
    LOG_FILENAME, maxBytes=50000, backupCount=2)

#  Add smtp handler
email_info = {
    "mailhost": '{}:{}'.format(config.email["host"], config.email["port"]),
    "fromaddr": ['robot@example.com'],
    "toaddrs": ['egis@example.com'],
    "subject": 'Kraken escaped!',
    "credentials": (config.email["username"], config.email["passwd"]),
    "secure": (),
}
smtp_handler = logging.handlers.SMTPHandler(**email_info)

formatter = logging.Formatter(
    '<%(asctime)s - %(name)s - %(levelname)s> %(message)s')

file_handler.setFormatter(formatter)
smtp_handler.setFormatter(formatter)

app_logger.addHandler(file_handler)
app_logger.addHandler(smtp_handler)






# Filename: my_app/delivery/controllers.py

import logging

logger = logging.getLogger(__name__)

# ... and when exceptions occurs I do following (in except statement)

logger.exception(exc)

# As I've said - it gets logged to a file, but email is not sent (fails silently?).

我做错了什么?

1 个答案:

答案 0 :(得分:0)

所以......我应该更仔细地阅读文档。它声明如果端口不是默认的&#39;那么mailhost参数应该是(hostname, port)元组而不是&#39; hostname:port&#39;字符串。

修复如下:

email_info = {
    "mailhost": (config.email["host"], config.email["port"]),
    #....
}