在Python中引入日志记录功能,你可以使用标准库中的`logging`模块。以下是使用`logging`模块的基本步骤:
1. 导入`logging`模块。
```python
import logging
2. 配置日志记录器。你可以设置日志记录的级别(如DEBUG、INFO、WARNING、ERROR、CRITICAL)和日志的格式。```pythonlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

3. 使用不同的日志级别记录日志消息。
```python
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')
以上代码将分别记录不同级别的日志消息。默认情况下,日志消息会输出到控制台。如果需要将日志写入文件,可以通过`FileHandler`添加文件处理器。```pythonfile_handler = logging.FileHandler('example.log')
file_handler.setLevel(logging.DEBUG)
logging.getLogger().addHandler(file_handler)
以上步骤展示了如何使用`logging`模块进行日志记录。
