Logging module in Python

Logging module in Python

The logging module in Python provides a flexible and powerful way to log messages from your Python code. It allows you to easily record information about the behavior of your application and makes it easier to diagnose problems when they occur.

Here are some key concepts and features of the logging module:

  1. Loggers: A logger is the main object in the logging module. It is used to emit log messages. You can create multiple loggers to organize your log messages into different categories.
  2. Handlers: A handler is responsible for taking the log messages emitted by a logger and processing them. The logging module provides several built-in handlers, such as StreamHandler, FileHandler, RotatingFileHandler, and SMTPHandler.
  3. Formatters: A formatter is used to specify the format of the log messages emitted by a handler. The logging module provides several built-in formatters, such as Formatter and JSONFormatter.
  4. Levels: Loggers and handlers have levels associated with them. When a logger or handler is created, you can specify a level. Only log messages with a level that is greater than or equal to the level of the logger or handler will be emitted. The logging module provides several built-in levels, such as DEBUG, INFO, WARNING, ERROR, and CRITICAL.

Here is an example of how to use the logging module to emit log messages:

pythonCopy codeimport logging

# create a logger
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)

# create a handler
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)

# create a formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# add the handler to the logger
logger.addHandler(handler)

# emit 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 code creates a logger named my_logger and sets its level to DEBUG, which means that it will emit all log messages. It also creates a StreamHandler that sends log messages to the console, sets its level to DEBUG, and sets a formatter that includes the time stamp, logger name, log level, and message. Finally, the code adds the handler to the logger and emits some log messages with different levels.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Share this post
[social_warfare]
DNS DHCP ARP and ICMP
Fragmentation and MTU

Get industry recognized certification – Contact us

keyboard_arrow_up