在Python中打印日志,推荐使用`logging`模块,因为它提供了更丰富的配置选项,比如输出到控制台或文件,并且支持日志级别控制。以下是使用`logging`模块打印日志的基本步骤:
1. 导入`logging`模块:
import logging
2. 配置日志记录器:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
这里`level`参数设置了日志的最低输出级别,`format`参数定义了日志的输出格式。
3. 输出不同级别的日志信息:

logging.debug('This is a debug message')logging.info('This is an info message')logging.warning('This is a warning message')logging.error('This is an error message')logging.critical('This is a critical message')
4. 如果需要将日志输出到文件,可以这样做:
创建日志对象log = logging.getLogger('mylogger')log.setLevel(logging.DEBUG)创建文件处理器file_handler = logging.FileHandler('test_logger.log', encoding='utf-8')file_handler.setLevel(logging.DEBUG)设置日志格式formatter = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')file_handler.setFormatter(formatter)添加文件处理器到日志记录器log.addHandler(file_handler)
以上代码将创建一个名为`mylogger`的日志记录器,配置其最低输出级别为`DEBUG`,并将日志信息输出到`test_logger.log`文件中,同时设置了日志的格式。
