How to do logging in Python

1 min

Logging in Python is the process of keeping track of events that happen in the program by outputting messages to a log file or a designated logging service. The built-in logging module in Python provides a flexible logging system for a wide range of purposes.

Here is an example of how to use the logging module in Python:

import logging

# Create a logger object
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# Create a file handler to output log messages to a file
file_handler = logging.FileHandler("program.log")
file_handler.setLevel(logging.INFO)

# Create a formatter to format the log messages
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
file_handler.setFormatter(formatter)

# Add the file handler to the logger
logger.addHandler(file_handler)

# Example usage of the logger
logger.info("Program started")

# Some code here

logger.info("Program ended")

This example sets up a logger with the name of the current module and sets the logging level to INFO.

Then it creates a file handler to write log messages to a file named program.log and set the logging level to INFO as well.

Then it creates a formatter to format the log messages and sets it to the file handler.

Finally, it adds the file handler to the logger and uses the logger to output log messages.

In addition, you can also use other handlers, such as StreamHandler to log messages to the console, and SMTPHandler to send log messages via email, and more.

It's also worth noting that you can use different logging levels to filter the messages, such as DEBUG, INFO, WARNING, ERROR, and CRITICAL.