Last active
October 4, 2021 08:16
-
-
Save dwerbam/0d9b75cd73f67b6bdead1b2f7ee41414 to your computer and use it in GitHub Desktop.
calculates the time difference between the log lines and writes the 'next' line with the prefixed time lapse
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
## calculates the time difference between the log lines | |
## and writes the 'next' line with the prefixed time lapse | |
## use: python3 logplapse.py some.log > ts.log | |
from datetime import datetime | |
import re | |
import sys | |
FMT = '%Y-%m-%d %H:%M:%S' | |
TS_REGEXP = '\[([0-9:\- ]+)\]' | |
SPACER = "| ".rjust(10) | |
if __name__ == '__main__': | |
last_ts = None | |
total_seconds = 0 | |
with open(sys.argv[1], "r") as f: | |
for line in f: | |
rline = line.rstrip() | |
m = re.search(TS_REGEXP, line) | |
if m == None: | |
print(rline) | |
continue | |
try: | |
new_ts = datetime.strptime(m.group(1), FMT) | |
except ValueError as err: | |
print(rline) | |
continue | |
if last_ts != None: | |
ts = new_ts - last_ts | |
if(ts.total_seconds()==0): | |
print(SPACER, rline) | |
else: | |
total_seconds += ts.total_seconds() | |
print(ts, "| ", rline) | |
else: | |
print(SPACER, rline) | |
last_ts = new_ts | |
print("Total seconds: ", total_seconds) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment