SMTPHandler in Python's logging module sending

2019-02-02 01:05发布

This question already has an answer here:

I'm attempting to use Python's logging module to send emails containing logs. The problem that I'm having is that each time I write a log entry, an email is sent. How do I queue the log messages and send a single email at the conclusion of the script?

I have a feeling that it's done with the emit() method, but I can't figure out how to use it.

import logging, logging.handlers
log = logging.getLogger("mylogger")
log.setLevel(logging.DEBUG)
h2 = logging.handlers.SMTPHandler(mailhost='mailserver',
                            fromaddr='noreply@example.com',
                            toaddrs=['me@example.com'],
                            subject='The log',
                            credentials=('user','pwd'),
                            secure=None)
h2.setLevel(logging.INFO)
h2.setFormatter(f)
log.addHandler(h2)

log.info("Did something")
log.info("Did something else")
log.info("This would send a third email. :-(")

2条回答
聊天终结者
2楼-- · 2019-02-02 01:42

See this answer which I gave for a similar question. An example handler to use is here; you can adapt it to your requirements.

查看更多
再贱就再见
3楼-- · 2019-02-02 01:49

Simply subclass SMTPHandler in order to produce the wanted behavior. you could for example override the emit method in order to send a mail on every third logged message

Caution: Depending on the implementation you chose no mail at all would be sent if you do log only one or two times. Perhaps a delayed sending could be the solution: Wait a second before you send the mail. If after a second no other line is received, then send it else add the line to the message to be send and wait another second ... and so on... (Delayed sending must be done in a separate thread (consider using Timer)

查看更多
登录 后发表回答