Created
September 10, 2020 11:52
-
-
Save rs0h/69c44118c7ac3b650d18dcfe2a884c5f to your computer and use it in GitHub Desktop.
PostgreSQL log parse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import re | |
| import argparse | |
| parser = argparse.ArgumentParser(description='PostgreSQL log parser. Will split logfile to multiple by sessionid and ip address') | |
| parser.add_argument('filename', help='PosgreSQL log file') | |
| args = parser.parse_args() | |
| filename = args.filename | |
| c = re.compile(r'\[(\d+)\].*connection received.*=(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})') | |
| cs = re.compile(r'\[(\d+)\]') | |
| sessions = {} | |
| lastOut = None | |
| with open(filename, 'r') as f: | |
| for line in f: | |
| m = c.search(line) | |
| if (m): | |
| sess = int(m.group(1)) | |
| ip = m.group(2) | |
| sessFileName = '{0}_{1}.log'.format(sess, ip) | |
| out = open(sessFileName, 'a') | |
| sessions[sess] = out | |
| m = cs.search(line) | |
| if (m): | |
| sess = int(m.group(1)) | |
| if (sess not in sessions): | |
| lastOut = None | |
| else: | |
| out = sessions[sess] | |
| out.write(line) | |
| lastOut = out | |
| elif (lastOut is not None): | |
| lastOut.write(line) | |
| print('Sessions count={0}'.format(len(sessions.keys()))) | |
| for sess, handle in sessions.items(): | |
| handle.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment