import logginglogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')logging.debug("This is a debug message")logging.info("This is an info message")logging.warning("This is a warning message")
2025-02-10 13:12:50,256 - DEBUG - This is a debug message
2025-02-10 13:12:50,259 - INFO - This is an info message
2025-02-10 13:12:50,260 - WARNING - This is a warning message
console_handler = logging.StreamHandler()console_formatter = logging.Formatter('%(levelname)s - %(message)s') # Simple format for consoleconsole_handler.setFormatter(console_formatter)logger.addHandler(console_handler)logger.debug("a debug msg going to file and console")logger.info("an info msg to file and console")
DEBUG - a debug msg going to file and console
INFO - an info msg to file and console
4. Multiple Loggers and Hierarchy
import logginglogging.basicConfig(level=logging.DEBUG) # root loggerapp_logger = logging.getLogger("my_app") # main app loggerapp_logger.setLevel(logging.INFO)module1_logger = logging.getLogger("my_app.module1")# specific module loggermodule1_logger.setLevel(logging.DEBUG)module2_logger = logging.getLogger("my_app.module2") # Logger for another modulemodule2_logger.setLevel(logging.WARNING)app_logger.info("This is an info message from the main app") module1_logger.debug("This is a debug message from module 1")module2_logger.warning("This is a warning message from module 2")