# -*- coding: utf-8 -*- import datetime # This is needed in a global context once DATE_TODAY = datetime.datetime.now() class GenericPostfixLogLine(): raw_line = None date = None hostname = None service_prefix = None service_suffix = None pid = None unparsed_part = None def __init__(self, line): self.raw_line = line.replace('\n', '') fields = self.raw_line.split(' ') datefield = ' '.join(fields[0:3]) line_date = datetime.datetime.strptime(datefield, "%b %d %H:%M:%S") self.date = line_date.replace(year=DATE_TODAY.year) self.hostname = fields[3] service = fields[4][:-1] if '/' in service: service_parts = service.split('/') self.service_prefix = service_parts[0] service_suffix_parts = service_parts[1].split('[') self.service_suffix = service_suffix_parts[0] self.pid = service_suffix_parts[1].replace(']', '') else: # Cannot handle this kind of line. :/ pass self.unparsed_part = " ".join(fields[5:]) def __repr__(self): return str(self.raw_line) class SmtpPostfixLogLine(): def __init__(self, generic_line): self.generic_line = generic_line def parse_line(line): generic = GenericPostfixLogLine(line) if generic.service_suffix == None: return generic elif generic.service_suffix == 'smtp': return SmtpPostfixLogLine(generic) if __name__ == '__main__': filename = '/home/jpt/Testdata/postfix-log.txt' file = open(filename, 'r') lines = file.readlines() res = parse_line(lines[0]) print(res) import pdb; pdb.set_trace()