我想知道是否可以拦截日志记录调用以根据级别发送电子邮件或短信。
请记住,在电子邮件和短信下,还有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")
答案 0 :(得分:2)
您可以使用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')