python - Python - 读取日志文件,分析它并打印出行,具体取决于操作
问题描述
我需要有关如何创建分析日志文件的 Python 脚本的想法的帮助。
目标是运行:python3 analyzer.py [filepath] [action]
它应该打印出:每行中的错误或通知,具体取决于操作。
filepath
- 日志文件的路径
- 动作的有效值是错误,注意。
- 该操作确定脚本输出的内容。
action
- error = 打印文件中的错误
- notice = 在文件中打印通知
这家伙有类似的:分析日志文件时如何获得所有行的输出?
到目前为止尝试过这个。
import argparse
# class errors(argparse.Action):
# def __call__(self, parser, namespace, values, option_string=None):
# setattr(namespace, self.dest, ' '.join(values))
# parser = argparse.ArgumentParser(description='Parse input string')
# parser.add_argument('string', help='Input String', nargs='+', action=errors)
# parser.add_argument('--extra', '-s', help='Another Option!')
# args = parser.parse_args()
# print(args)
error = {}
notice = {}
log_file = 'log.log'
# Functions
def load():
with open('log.log') as logfile:
for line in logfile:
parts = line.split('[error]')
if len(parts) == 2:
error[parts[0]] = parts[1]
parts = line.split('[notice]')
if len(parts) == 2:
notice[parts[0]] = parts[1]
def errors():
for date, info in error.items():
print(date + ' : ' + info)
def notices():
for date, info in notice.items():
print(date + ' : ' + info)
if __name__ == "__main__":
load()
日志文件log.log 示例:
[Mon Jan 01 09:01:48 2021] [error] Cannot delete topic 1
[Mon Jan 01 09:01:48 2021] [notice] Scheduling log segment 564002 for log test-0 for deletion. (kafka.log.Log)
[Mon Jan 01 09:01:48 2021] [error] Cannot delete topic 2
[Mon Jan 01 09:01:48 2021] [notice] <powershell> topic was provided.. running powershell content
[Mon Jan 01 09:01:48 2021] [error] Cannot delete topic 3
[Mon Jan 01 09:11:40 2021] [notice] creating topics
[Mon Jan 01 09:11:43 2021] [error] [client 091.154.18.244] Directory index forbidden by rule: /var/www/ ```
解决方案
首先尝试此代码。
它使用您现有的循环并查看该值是否[error]
出现在一行上,如果出现则将其打印出来。
with open('log.log') as logfile:
for line in logfile:
if "[error]" in line:
print(line)
假设这可行,扩展您的代码以允许来自参数的值应该相对简单。
以下是您可能想要更改的提示:
action = "error"
...
if f"[{action}]" in line:
print(line)
推荐阅读
- sql - 查找特定列的上一季度的非空数据
- oracle - ORACLE 使用过滤器和数据透视表的程序代码
- for-loop - 如何编写一个计算字符串中每个字符的函数?
- android - Android - AsyncTask 之后的 Intent 数据
- google-cloud-platform - 是否可以创建 GCP 内部负载均衡器以桥接共享 VPC 和单独的 GCP VPC?
- r - 在 r markdown 中迭代地打印出 r 块内的表
- c - 获取 csv 记录的无效指针
- azure - 如何捕获控制台服务主机的关键性能指标,包括:AppInsights 中的 CPU 利用率、内存利用率
- api - 使用外键的 ASP.NET Core Web API
- javascript - 收到 ajax 响应后使用 const 变量