Today we’re going to talk about one of my favorite modules: logging. This built-in module is super powerful and can help you debug your code like a pro. But let’s not get ahead of ourselves first things first, what exactly is the logging module?
In simple terms, it’s a tool that allows you to log messages in your Python application. These logs can be used for various purposes such as tracking errors or monitoring performance. The best part about this module is that it’s already included in Python, so there’s no need to install any external libraries!
Now Let’s kick this off with the details of how to use logging. First, you can import the logging module by adding `import logging` at the beginning of your script. Once that’s done, you can create a logger object using the `getLogger()` function:
# Import the logging module
import logging
# Create a logger object using the getLogger() function
logger = logging.getLogger(__name__)
# The getLogger() function returns a logger object with the specified name, in this case, the name of the current module.
# The logger object can then be used to log messages at different levels, such as debug, info, warning, error, and critical.
# To log a message, we can use the methods provided by the logger object, such as logger.debug(), logger.info(), logger.warning(), logger.error(), and logger.critical().
# For example, we can use the logger.info() method to log an informational message:
logger.info("This is an informational message")
# We can also specify a message format using the basicConfig() function, which takes in parameters such as the format, datefmt, and level:
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)
# The above code will format the log messages to include the current date and time, the log level, and the message itself.
# Now, we can use the logger object to log messages at different levels, such as:
logger.debug("This is a debug message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")
# The log messages will be displayed in the console with the specified format and level.
# We can also specify a file to save the log messages using the basicConfig() function, by adding the filename parameter:
logging.basicConfig(filename='mylog.log', format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)
# This will save the log messages to a file named "mylog.log" in the same directory as the script.
# In summary, the logging module allows us to log messages at different levels and formats, making it easier to debug and monitor our code.
This line creates a new logger with the name of the current module (in this case, it would be whatever file or script you’re currently working on). If you want to log messages from multiple modules, just create separate logger objects for each one!
Now that we have our logger object, let’s actually start logging some stuff. You can do this by using the `logger` object and its various methods:
# Import the logging module
import logging
# Create a logger object with the name 'my_logger'
my_logger = logging.getLogger('my_logger')
# Set the logging level to DEBUG
my_logger.setLevel(logging.DEBUG)
# Create a console handler and set its logging level to DEBUG
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
# Create a formatter and add it to the console handler
formatter = logging.Formatter('%(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
# Add the console handler to the logger object
my_logger.addHandler(console_handler)
# Log messages using the logger object and its various methods
my_logger.debug('This is a debug message') # Logging level: DEBUG (lowest priority)
my_logger.info('This is an info message') # Logging level: INFO (higher than DEBUG, lower than WARNING)
my_logger.warning('This is a warning message') # Logging level: WARNING (higher than INFO, lower than ERROR)
my_logger.error('This is an error message') # Logging level: ERROR (highest priority for errors and exceptions)
my_logger.critical('This is a critical message') # Logging level: CRITICAL (highest priority for fatal errors)
Each of these methods takes in the log message as its argument, which can be any string or object that you want to log. The logging module automatically determines what type of message it is based on the method used and assigns a level to it accordingly.
But wait there’s more! You can also customize your logger by setting up handlers for it. Handlers are responsible for sending the logged messages to their destination, whether that be a file or console output. Here’s an example:
# Import the logging module
import logging
# Import the FileHandler class from the logging module
from logging import FileHandler
# Create a logger object with the name of the current module
logger = logging.getLogger(__name__)
# Create a FileHandler object and specify the filename for the log file
handler = FileHandler('my_log.txt')
# Create a formatter object to specify the format of the log messages
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
# Set the formatter for the FileHandler object
handler.setFormatter(formatter)
# Add the FileHandler object to the logger
logger.addHandler(handler)
# The above code sets up a logger with a FileHandler to send log messages to a specified file.
# The logger is named after the current module and the FileHandler is set to use a specific format for the log messages.
In this example, we’re creating a new logger object and adding a FileHandler to it. The `FileHandler()` function takes in the filename for your log file as its argument (in this case, ‘my_log.txt’). We also set up a formatter using the `Formatter()` function, which specifies how each logged message should be displayed when it’s written to the log file.
And that’s it! You now have a fully customized logger object with handlers and everything. But wait there’s even more you can do with logging! For example, you can set up multiple handlers for your logger object or filter out certain messages based on their level. The possibilities are endless!