# 记录不同级别的日志 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')
控制台输出:
1 2 3 4 5
2024-09-17 20:46:41,803 - basic_logger - DEBUG - This is a DEBUG message 2024-09-17 20:46:41,803 - basic_logger - INFO - This is an INFO message 2024-09-17 20:46:41,803 - basic_logger - WARNING - This is a WARNING message 2024-09-17 20:46:41,803 - basic_logger - ERROR - This is an ERROR message 2024-09-17 20:46:41,803 - basic_logger - CRITICAL - This is a CRITICAL message
2024-09-17 20:53:46,430 - exception_logger - ERROR - An exception occurred Traceback (most recent call last): File "/home/issey/workplace/Docker_workplace/Logger_Study/Course03/log_exception.py", line 32, in <module> result = 10 / 0 ZeroDivisionError: division by zero
# 记录主文件日志 logger.info('This is an INFO message from main')
# 调用模块函数 function_a() function_b()
module_a.py:
1 2 3 4 5 6 7 8 9 10 11 12 13
import logging
# 创建模块 A 的日志记录器 logger = logging.getLogger('module_a')
deffunction_a(): logger.debug('This is a DEBUG message from module A') logger.info('This is an INFO message from module A') logger.warning('This is a WARNING message from module A') try: result = 10 / 0 except ZeroDivisionError: logger.exception('Exception occurred in module A')
module_b.py:
1 2 3 4 5 6 7 8 9 10 11 12 13
import logging
# 创建模块 B 的日志记录器 logger = logging.getLogger('module_b')
deffunction_b(): logger.debug('This is a DEBUG message from module B') logger.info('This is an INFO message from module B') logger.warning('This is a WARNING message from module B') try: result = [1, 2, 3][5] except IndexError: logger.exception('Exception occurred in module B')
2024-09-17 21:12:26,607 - main - INFO - This is an INFO message from main 2024-09-17 21:12:26,608 - module_a - DEBUG - This is a DEBUG message from module A 2024-09-17 21:12:26,608 - module_a - INFO - This is an INFO message from module A 2024-09-17 21:12:26,608 - module_a - WARNING - This is a WARNING message from module A 2024-09-17 21:12:26,608 - module_a - ERROR - Exception occurred in module A Traceback (most recent call last): File "/home/issey/workplace/Docker_workplace/Logger_Study/Course03/module_a.py", line 11, in function_a result = 10 / 0 ZeroDivisionError: division by zero 2024-09-17 21:12:26,608 - module_b - DEBUG - This is a DEBUG message from module B 2024-09-17 21:12:26,608 - module_b - INFO - This is an INFO message from module B 2024-09-17 21:12:26,609 - module_b - WARNING - This is a WARNING message from module B 2024-09-17 21:12:26,609 - module_b - ERROR - Exception occurred in module B Traceback (most recent call last): File "/home/issey/workplace/Docker_workplace/Logger_Study/Course03/module_b.py", line 11, in function_b result = [1, 2, 3][5] IndexError: list index out of range