gpt4 book ai didi

Python 日志记录 SMTPHandler 不工作

转载 作者:行者123 更新时间:2023-12-01 09:33:23 24 4
gpt4 key购买 nike

我已经在 Python 3 中完成并尝试了这段代码,以便在发生异常时向我发送电子邮件,但 STMPHandler 不起作用。它与 SMTPHandler 的相同参数和值以及从此 answer 复制粘贴的相同代码完美配合。

工作代码:

import logging.handlers

smtp_handler = logging.handlers.SMTPHandler(mailhost=("smtp.gmail.com", 587),
fromaddr="somemail@gmail.com",
toaddrs="anothermail@gmail.com",
subject=u"Alfred error!",
credentials=("somemail@gmail.com", "asdasdasdasdasd"),
secure=())


logger = logging.getLogger()
logger.addHandler(smtp_handler)

try:
raise Exception()
except Exception as e:
logger.exception('Unhandled Exception')

所有处理程序都运行良好,并且答案中的代码仅适用于 exception() 调用。

我不明白为什么这不起作用。

log_config.py(无效代码):

import os

import logging
import logging.handlers

version = "2.0.0"
LOGFILE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'log', 'my_app.log')
logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.DEBUG)
logging.getLogger('telegram').setLevel(logging.WARNING)
logging.getLogger('chardet.charsetprober').setLevel(logging.WARNING)


class TimedOutFilter(logging.Filter):
def filter(self, record):
if "Error while getting Updates: Timed out" in record.getMessage():
return False


def getLogger(name):
"""
Return a logger for the file
:param name: the file name
:return: a logger
"""
global version
logger = logging.getLogger(name)

fh = logging.handlers.TimedRotatingFileHandler(LOGFILE_PATH, when='midnight')
formatter = logging.Formatter('%(asctime)s - ({0}) %(name)s - %(levelname)s - %(message)s'.format(version))
fh.setFormatter(formatter)
fh.addFilter(TimedOutFilter())
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)

if os.environ.get('SERVER', True):
mh = logging.handlers.SMTPHandler(mailhost=("smtp.gmail.com", 587),
fromaddr="somemail@gmail.com",
toaddrs="anothermail@gmail.com",
subject=u"Alfred error!",
credentials=("somemail@gmail.com", "asdasdasdasdasd"),
secure=())
mh.setFormatter(formatter)
mh.addFilter(TimedOutFilter())
mh.setLevel(logging.ERROR)
logger.addHandler(mh)

ch = logging.StreamHandler()
formatter = logging.Formatter('{0} %(levelname)s - %(message)s'.format(version))
ch.setFormatter(formatter)
ch.addFilter(TimedOutFilter())
ch.setLevel(logging.ERROR)
logger.addHandler(ch)

return logger


if __name__ == '__main__':
logger = getLogger(__name__)
try:
raise Exception()
except Exception as e:
logger.exception('Unhandled Exception')
logger.error('an error line')
logger.debug('a debug line')

最佳答案

timedOutFilter 毁了一切,因为它只返回 False,但从未返回 True。

所以只是做:

class TimedOutFilter(logging.Filter):
def filter(self, record):
if "Error while getting Updates: Timed out" in record.getMessage():
return False
return True # <==== Added this line only

解决了整个问题。

关于Python 日志记录 SMTPHandler 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49760576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com