gpt4 book ai didi

python拦截日志记录到电子邮件或短信

转载 作者:行者123 更新时间:2023-11-30 23:14:49 25 4
gpt4 key购买 nike

我想知道是否可以拦截日志记录调用以根据级别发送电子邮件或短信。

请记住,在电子邮件和短信下,还有可能导致循环的logging.error

import logging, smtplib, urllib2

LOGGER = 'log.out'
FORMAT = '%(asctime)s %(levelname)s %(message)s'
LEVEL = logging.INFO

logging.basicConfig(filename=LOGGER, format=FORMAT, maxBytes=2048, level=LEVEL)

def email(_msg):
try:
email_mesg = "Subject:{0}\n\n{1}".format(email_subj, _msg)
s = smtplib.SMTP(email_host)
s.sendmail(email_from, email_recv, email_mesg)
s.quit()
except smtplib.SMTPException as e:
logging.error(e)

def sms(_msg):
try:
sms_mesg = urllib2.quote(_msg)
url = "https://smsapi/?username={0}&password={1}&message={2}&orig={3}&number={4}".format(sms_user, sms_pass, sms_mesg, sms_orig, sms_numb)
req = urllib2.Request(url)
res = urllib2.urlopen(req)
except urllib2.URLError as e:
logging.error(e)

if __name__ == "__main__":
"""
The following line should log and trigger email
"""
logging.warning("Something you should know about")

"""
The following line should log and trigger sms
"""
logging.error("Something you should know about")

最佳答案

您可以使用Filter :

import sys, logging

class SMSEmailFilter(logging.Filter):
def filter(self, record):
if not record.args:
if record.levelno == logging.WARN:
email(record.msg)
elif record.levelno >= logging.ERROR:
sms(record.msg)
return True

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', stream=sys.stdout)
logger = logging.getLogger()
logger.addFilter(SMSEmailFilter())


def email(_msg):
try:
print "Sending email..."
except:
logger.error('from email', {'a': 1})


def sms(_msg):
try:
print "Sending sms..."
except:
logger.error('from sms', {'a': 1})


logger.warning('This is a warning')
logger.error('This is an error')

关于python拦截日志记录到电子邮件或短信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28603159/

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