How to Create a Logger in Python?

Estimated read time 2 min read

Creating a logger in Python involves the following steps:

  1. Import the logging module: Start by importing the built-in logging module in your Python code.
  2. Configure the logger: You can configure the logger using various methods like basicConfig() or dictConfig(). This step is optional, but it’s recommended to set the level of logging, the output format, and the destination to log messages to.
  3. Create a logger instance: Create an instance of the logger using logging.getLogger(name), where name is the name of the logger. This step is optional if you’re using the root logger.
  4. Log messages: Use the methods of the logger instance to log messages at different levels, such as debug(), info(), warning(), error(), or critical().

Here’s an example of how to create a logger in Python:

import logging

# Configure the logger
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='example.log', filemode='w')

# Create a logger instance
logger = logging.getLogger('my_logger')

# Log messages
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')

This example configures the logger to output messages at the DEBUG level or higher, in a format that includes the time, level, and message. The messages are logged to a file called example.log in write mode, meaning that the file will be overwritten every time the logger is used.

The logger instance is created with the name 'my_logger', although this is optional. Finally, the logger instance is used to log messages at various levels using the corresponding methods.

Note that you can also log messages to the console using a StreamHandler, or to multiple destinations using multiple handlers. Additionally, you can customize the logging behavior further by creating custom loggers and handlers.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply