python读取log文件
时间: 2023-10-09 18:04:48
浏览: 176
要Python中读取log文件,可以使用Python的内置库来实现。以下是一个示例[代码](https://geek.csdn.net/educolumn/1572ef9b473b4e00f6b2bf6d428b7c27?spm=1055.2569.3001.10083),演示了如何读取log文件:
```python
import logging
# 创建日志记录器
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# 设置日志输出格式
format = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d %(levelname)s %(message)s')
# 创建一个[han](https://geek.csdn.net/educolumn/0d22b54eaf6bcf967d9625e1679d00b4?spm=1055.2569.3001.10083)dler用于将日志写入文件
logFile = './log.txt'
fh = logging.File[han](https://geek.csdn.net/educolumn/0d22b54eaf6bcf967d9625e1679d00b4?spm=1055.2569.3001.10083)dler(logFile, mode='a', encoding='utf-8')
fh.setLevel(logging.INFO)
fh.setFormatter(format)
logger.add[han](https://geek.csdn.net/educolumn/0d22b54eaf6bcf967d9625e1679d00b4?spm=1055.2569.3001.10083)dler(fh)
# 读取log文件
with open(logFile, 'r', encoding='utf-8') as file:
log_data = file.readlines()
# 打印log内容
for line in log_data:
print(line.strip())
请注意,需要将上述[代码](https://geek.csdn.net/educolumn/1572ef9b473b4e00f6b2bf6d428b7c27?spm=1055.2569.3001.10083)中的`./log.txt`替换为实际的log文件路径。此代码将读取log文件的内容,并逐行打印出来。<span class="em">1</span><span class="e