Python to read Oracle alert.log

I’m used to working in a UNIX environment and when I was asked to build a database and manage on Windows, I was faced with some new challenges. One of them is searching through the Alert log and without standard UNIX grep I wanted to write something that could perform the same function. Also show the log from a timestamp. Here it goes:

import datetime
import time
import traceback
import io
import sys

def printer(*args):
return args

KeyWordList = ['*']
  
if len(sys.argv) == 1:
    SkipMins = 360
elif len(sys.argv) == 2:
    SkipMins = int(sys.argv[1])
elif len(sys.argv) >= 3:
    SkipMins = int(sys.argv[1])
    KeyWordList = printer(sys.argv[2])     

print('Searching for',KeyWordList)
       
OutputList =[]
FoundDate = ""

CurrentDate = datetime.datetime.now()
SearchDate = datetime.datetime.now().strftime("%Y-%m-%d")


AlertLog=r'E:\App\oraservice\diag\rdbms\pcad9401\pcad9401\trace\alert_pcad9401.log'
SkipDelta=datetime.timedelta(minutes=SkipMins)

try:
    with io.open(AlertLog,mode='r') as f:
        for line in f:
            line=f.readline()
            if line[0:10] == SearchDate:
                EventDate = line[:-7]
                EventDate =  datetime.datetime.strptime(EventDate.rstrip('\n'),'%Y-%m-%dT%H:%M:%S.%f')
                FoundDate = True
            elif FoundDate == True:
                if CurrentDate-SkipDelta < EventDate:
                    if '*' not in KeyWordList:
                        for w in KeyWordList:
                            if w in line:
                                OutputList.append([EventDate,line.rstrip('\n')])
                    else:
                        OutputList.append([EventDate,line.rstrip('\n')])
except:
    print(traceback.format_exc())
                   
for o in OutputList:
    print('[%s] %s' % (o[0],o[1]))     
print('Found',len(outputList),'records')

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.