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. :-(")
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 .
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.
See this answer which I gave for a similar question. An example handler to use is here; you can adapt it to your requirements.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With