Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send email with Python logging

I'd like to send an email everytime Logger.fatal or Logger.warn is invoked.

Perhaps a solution could be to extend it and override the methods. But when you import logging, the only way to get a Logger class is using logging.getLogger().

How do I solve this?

like image 555
Jekk Avatar asked Oct 27 '25 15:10

Jekk


1 Answers

It's not a best solution to override logger methods.

Python logging configuration supports multiple loggers which then support multiple handlers (files, stdout, email). Handlers in turn have different formatters (string format how log entry is displayed), but it's offtopic for this question.

In fact Python supports email logging out of the box through SMTPHandler.

Because you did not include details about your application and logger setup it is not possible to give answer specific to your question. But generally outline is this

  • Add a SMTPHandler handler root logger (call logging.getLogger() with arguments should give you the root lgoger)

  • Make the handler level WARN so that it ignores INFO, and DEBUG levels

See also proper mechanism to initialize loggers in your Python code.

like image 111
Mikko Ohtamaa Avatar answered Oct 29 '25 05:10

Mikko Ohtamaa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!