Log to Console, File and SMTP With Logging Module
In this post I will show you how to use the logging module to log messages to console, file as well as send email using smtp, depending on the level of the message
Create a logger
First we will create a logger and set level to DEBUG
import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG)
Create the handlers
Then we create and add to the logger a FileHandler, StreamHandler (console) and SMTPHandler. I will use for smtp my localhost, you have to replace the details with the details of your smtp server. The error.log should be in a place where you have write permissions.
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') consoleHandler = logging.StreamHandler(sys.stdout) consoleHandler.setLevel(logging.DEBUG) consoleHandler.setFormatter(formatter) fileHandler = logging.handlers.RotatingFileHandler(filename="error.log",maxBytes=1024000, backupCount=10, mode="a") fileHandler.setLevel(logging.INFO) fileHandler.setFormatter(formatter) smtpHandler = logging.handlers.SMTPHandler( mailhost = "localhost", fromaddr = "alerts@localhost", toaddrs = "geo555@localhost", subject = "alert!" ) smtpHandler.setLevel(logging.CRITICAL) smtpHandler.setFormatter(formatter)
add the handlers to the logger
logger.addHandler(consoleHandler) logger.addHandler(fileHandler) logger.addHandler(smtpHandler)
call the logger with different levels
Finally in our main function we call the logger with three different levels. Because Console handler is set at DEBUG will get all messages. File Handler is set to info, so it will get two messages and email handler will only get the critical message
def main(): #this will be written only to console" logger.debug("this is a debug message") #this will be written to console and file logger.info("this is an info message") #this will go to email only logger.critical("Situation is critical. Come to office immediately.")
2020-12-09 22:22:01,384 - __main__ - DEBUG - this is a debug message 2020-12-09 22:22:01,384 - __main__ - INFO - this is an info message 2020-12-09 22:22:01,384 - __main__ - CRITICAL - Situation is critical. Come to office immediately.
2020-12-09 22:22:01,384 - __main__ - INFO - this is an info message 2020-12-09 22:22:01,384 - __main__ - CRITICAL - Situation is critical. Come to office immediately.
In another post, I will show you how to use a dictionary and a yaml file as ways to configure the logger as well as how to use logger with packages.