[Python Snippet] - Retrieve and Parse Most Recent Log file Generated by Scripting API

Hope someone who needs this sees it.

This code will ftp into your account, download the most recent log, search for a string and list results. Still needs a lot of work,but at least you don't need a set up a webserver and trade jsons to get status codes.

use something like:

"onRinging": lambda event : log("ringingnow")

This will script will match the logged text.




import requests
import ftplib
import re
import datetime
import time
import pytz

#launch tropo hosted script
payload = {'action': 'create', 'token': '*replacewithapplicationtoken*'}

#error codes from http post
r = requests.post('https://api.tropo.com/1.0/sessions?', params=payload)

#wait for end of call

#check log file for great justice
#ftp connect and dir list
f = ftplib.FTP('ftp.tropo.com')
f.login('username', 'password')

data = []

#get filename from ftp dir output
#this will fail if logs have been archived to .gz
#launch application again
output = data[0]
print output
filename = output[-19:]
print filename

#write logfile
logf = open('logfile.txt', 'wb')
f.retrbinary('RETR ' + filename, logf.write, 1024)

#get current day and hour for regex
now = datetime.datetime.now(pytz.timezone('UTC'))
stamp = now.strftime("%d %H")
print stamp

#regex = re.compile(r'[a-zA-Z]+ *{}[a-zA-Z]+_state=ANSWERED'.format(stamp))
success = re.compile(r'({}:)+.+(\sringingnow)'.format(stamp))
fail = re.compile(r'({}:)+.+(\sError100)'.format(stamp))

#print regex1
#print regex2

with open('logfile.txt') as log:
lines = log.readlines()
for line in lines:
for m in re.findall(success, line):
print line
for n in re.findall(fail, line):
print line




1 comment

Please sign in to leave a comment.