使用Python的`logging`模块记录日志的基本步骤如下:
导入模块
```python
import logging
配置日志记录器
```python
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
这里配置了日志记录级别为`INFO`,并指定了日志格式,包括时间、记录器名称、日志级别和日志消息。
记录日志
```python
logging.info('This is an info log')
logging.warning('This is a warning log')
使用不同的日志记录级别(如`DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`)记录不同严重程度的事件。
输出到控制台
```python
logger = logging.getLogger('example')
logger.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
创建一个名为`example`的日志记录器,设置日志级别为`DEBUG`,创建一个控制台处理器,将日志输出到控制台,并应用日志格式。
输出到文件
```python
logging.basicConfig(filename='example.log', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
配置日志记录器将日志保存到文件`example.log`中,日志级别设置为`DEBUG`。
手动调整日志级别
```python
在命令行传入参数
python your_script.py --log-level DEBUG
以上是使用Python的`logging`模块记录日志的基本方法。您可以根据需要调整日志级别、输出目的地和日志格式