从多个服务器中查找最新的日志文件

时间:2020-01-21 08:08:18

标签: python-3.x

对于我们的日常监视,我们需要访问特定应用程序的16台服务器,并在其中一台服务器上找到最新的日志文件(通常在前8台服务器上生成)。

问题在于该代码为我提供了每个服务器的最新文件,而不是提供整个服务器组中的最新日志文件。

此外,由于这是一个小时的活动,因此一旦处理了文件,便将其存档,因此许多服务器在特定时间没有任何日志文件。因此,在执行以下代码时,我得到-ValueError: max() arg is an empty sequence响应,如果服务器4没有任何日志文件,则代码在服务器3处停止。

我尝试将default = 0参数添加到latest_file,但这给我错误消息TypeError: expected str, bytes or os.PathLike object, not int

您能在这里帮我吗?我正在使用Python 3.8和PyCharm。

这是我到目前为止所拥有的:

import glob
import os
import re

paths = [r'\\Server1\Logs\*.log',
         r'\\Server2\Logs\*.log',
         .....
         r'\\Server16\Logs\*.log']


for path in paths:
    list_of_files = glob.glob(path)
    latest_file = max(list_of_files, key=os.path.getctime)
    f = open(os.path.join(latest_file), "r")
    print(latest_file)

1 个答案:

答案 0 :(得分:1)

首先创建列表,然后找到最大值。

import glob
import os
import re

paths = [r'\\Server1\Logs\*.log',
         r'\\Server2\Logs\*.log',
         .....
         r'\\Server16\Logs\*.log']

list_of_files = []
for path in paths:
    list_of_files.extend(glob.glob(path))

if list_of_files:
    latest_file = max(list_of_files, key=os.path.getctime)
    f = open(os.path.join(latest_file), "r")
    print(latest_file)
else:
    print("No log files found!")
相关问题