Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SMTPHandler in Python's logging module sending emails one at a time. How can I stop this? [duplicate]

Tags:

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='[email protected]',
                            toaddrs=['[email protected]'],
                            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. :-(")
like image 362
jamieb Avatar asked Nov 19 '11 03:11

jamieb


People also ask

How do you clear a Python log file?

You'd have to signal to the daemon that the log file's been removed so it can close/reopen the log file handle and start using the new log file. Otherwise it'll just keep writing to the old one, which will still exist somewhere until all filehandles on it are closed. Give mode="w" to logging. FileHandler .

How does logging module work Python?

The Logging Module It is used by most of the third-party Python libraries, so you can integrate your log messages with the ones from those libraries to produce a homogeneous log for your application. With the logging module imported, you can use something called a “logger” to log messages that you want to see.


2 Answers

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

like image 105
Vinay Sajip Avatar answered Sep 19 '22 16:09

Vinay Sajip


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)

like image 20
gecco Avatar answered Sep 20 '22 16:09

gecco