python读取log文件
时间: 2023-10-09 12:04:48 浏览: 216
要Python中读取log文件,可以使用Python的内置库来实现。以下是一个示例代码,演示了如何读取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')
# 创建一个Handler用于将日志写入文件
logFile = './log.txt'
fh = logging.FileHandler(logFile, mode='a', encoding='utf-8')
fh.setLevel(logging.INFO)
fh.setFormatter(format)
logger.addHandler(fh)
# 读取log文件
with open(logFile, 'r', encoding='utf-8') as file:
log_data = file.readlines()
# 打印log内容
for line in log_data:
print(line.strip())
```
请注意,需要将上述代码中的`./log.txt`替换为实际的log文件路径。此代码将读取log文件的内容,并逐行打印出来。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [Python日志采集](https://blog.csdn.net/Asaasa1/article/details/109447299)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文