# -*- coding: iso-8859-1 -*-#

import pyparsing as pyp
import email

class ParseLog:
    def __init__(self):
        dayAbbr = pyp.Word(pyp.alphas)
        monthAbbr = pyp.Word(pyp.alphas)
        dayNo = pyp.Word(pyp.nums)
        yearNo = pyp.Word(pyp.nums)
        hourMin = pyp.OneOrMore(pyp.Word(pyp.nums) + ':')
        timeInfo = hourMin + pyp.Word(pyp.nums)
        dateAndTime = dayAbbr + monthAbbr + dayNo + timeInfo + yearNo
        
        aLogEntry = pyp.Suppress("[") + pyp.Combine(dateAndTime, adjacent=False) + pyp.Suppress("]") + pyp.restOfLine
        
        aLine = pyp.Suppress("[") + dateAndTime + pyp.Suppress("]") + pyp.restOfLine

        # log entry
        str_log = aLogEntry
        log = str_log.setParseAction(self.str_logAction)
        str_log.setDebug()
        
        # a line
        str_line = aLine
        line = str_line.setParseAction(self.str_lineAction)
        str_line.setDebug()

##        self.grammar = str_log + str_line # do both of them
        self.grammar = str_log | str_line # do the first match

    def str_logAction(self, s, l, t):
        self.dateStamp = ''
        self.logString = ''
        
        print 'log ====='
        for x in t:
            print x

    def str_lineAction(self, s, l, t):
        
        print 'line ======'
        for x in t:
            print x

    def doParseing(self, logfile):
        self.grammar.transformString(logfile)

if __name__ == "__main__":
    logFile = r'logfile.txt'
    thisfile = open(logFile, 'r')        

    u = ParseLog()
    u.doParseing(thisfile.read())
    
    thisfile.close()