Tutorial on Python logging: Understanding __name__ and logger inheritance

Posted by

Python logging tutorial: __name__ and logger inheritance

Python logging tutorial: __name__ and logger inheritance

In Python, logging is a very useful tool for debugging and monitoring the execution of your code. By using the built-in logging module, you can easily create log messages that can provide valuable information about the flow of your program.

__name__

One of the key concepts in Python logging is the use of the __name__ attribute. This attribute is automatically set by Python based on the name of the module or script in which the code is being executed. By using this attribute, you can easily distinguish between log messages from different parts of your program.

Logger inheritance

Logger inheritance is another important concept in Python logging. By creating a hierarchy of loggers, you can control the flow of log messages and define different levels of logging for different parts of your code. This can help you to organize and manage your log messages more effectively.

When creating a logger in Python, you can specify its name using the __name__ attribute. By using this attribute, you can ensure that log messages from different parts of your program are properly categorized and displayed in the log output.

Example:

  
  import logging
  
  logger = logging.getLogger(__name__)
  logger.setLevel(logging.DEBUG)
  
  handler = logging.StreamHandler()
  formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  handler.setFormatter(formatter)
  
  logger.addHandler(handler)
  
  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')
  
  

In this example, we create a logger using the __name__ attribute and set its logging level to DEBUG. We then add a stream handler to the logger and define a formatter to format the log messages. Finally, we log messages at different levels using the logger.

By following this tutorial and understanding the concepts of __name__ and logger inheritance, you can effectively use Python logging in your code to debug, monitor, and optimize your programs.

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@user-rs1il4ul8b
3 months ago

really helpful! The only thing that I think is missing is to clarify what is the convention about where to put the main logger configuration inside the project structure.

@guadalupe9581
3 months ago

Promo`SM

@djangodeveloper07
3 months ago

Try to provide real code examples instead of old school fashioned PPT stuff. looking forward for good videos