首页 > 解决方案 > Python - 读取日志文件,分析它并打印出行,具体取决于操作

问题描述

我需要有关如何创建分析日志文件的 Python 脚本的想法的帮助。

目标是运行:python3 analyzer.py [filepath] [action]

它应该打印出:每行中的错误或通知,具体取决于操作。

filepath

action

这家伙有类似的:分析日志文件时如何获得所有行的输出?

到目前为止尝试过这个。

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/ ```

标签: python

解决方案


首先尝试此代码。

它使用您现有的循环并查看该值是否[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)

推荐阅读