Question

Question: I'm trying to search a syslog (Linux server) for the first entry of an specific event and then execute a command (future development) and then log the information. I'm not sure if I have approached this the right way.

Problem: not sure how to exit the loop on the first valid entry found.

import os
import commands
from time import strftime

file = "server.log.1" # sample log
nlogFile =("/home/nsoper/log/logfile_%s.txt") %(strftime("%Y_%m_%d_ %H_%M_%S")) # create logfile
caption="SN" # sample serach
condition2 = "java error"


F=open(file, 'r')
nF=open(nlogFile, 'a')
nF.write("output for results search:\n\n")


print(strftime("%Y_%m_%d_ %H_%M_%S"))


for line in F:
       for item in line.split("\n"):
                 if caption in item:
                        line1=item.strip()
                        if condition2 in line1:
                                print line1.strip()
                                nF.write(line1.strip()+"\n")
                                #command execute


nF.close()
F.close()
Était-ce utile?

La solution

Here is the best way that I found to get this accomplished using python 2.4 (Linux prod env server. Not able/feaisble to upgrade python.) In this specific case I wanted to grab the last line, and then process it using another loop.

index=[]
con1 = "First Condition"
con2 = "Second Condition"

file=open("log.txt",'r')

print("Reading.. "+ file)
for line in F:
    for item in line.split("\n"):
            if con1 in item:
                    con1Line=item.strip()
                    if con2 in con1Line:
                            index.append(con1Line)
F.close()
l=index[-1]
print(l)
# do stuff now will value l
del index[:]
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top