OpenCog Framework  Branch: master, revision 6f0b7fc776b08468cf1b74aa9db028f387b4f0c0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
reorder_log.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 # Reorder chronologically a log.
4 
5 import re
6 import sys
7 import datetime
8 import argparse
9 
10 def datetime_from_str(time_str):
11  """Return <datetime.datetime() instance> for the given
12  datetime string given in OpenCog's date time log format
13  >>> _datetime_from_str("2009-12-25 13:05:14:453")
14  datetime.datetime(2009, 12, 25, 13, 5, 14, 453000)
15  """
16  fmt = "%Y-%m-%d %H:%M:%S:%f"
17  return datetime.datetime.strptime(time_str, fmt)
18 
19 if __name__ == "__main__":
20  parser = argparse.ArgumentParser(description='Reorder chronologically the log.')
21  parser.add_argument('logfile', help='Log file to reorder')
22  parser.add_argument('-o', '--output',
23  help='Output file. If unused stdout is used instead')
24  args = parser.parse_args()
25 
26  timestamp_re = r'\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}:\d{3})\]'
27  timestamp_prog = re.compile(timestamp_re)
28 
29  # Output file
30  of = open(args.output, "w") if args.output else sys.stdout
31 
32  # Put the structure in a dict (datetime, line number) -> chunk of text
33  dt2txt = {}
34  dt, dt_line_num = None, None
35  line_num = 0
36  for l in open(args.logfile):
37  m = timestamp_prog.match(l)
38  if m:
39  dt = datetime_from_str(m.group(1))
40  dt_line_num = line_num
41  dt2txt[(dt, dt_line_num)] = l
42  elif dt:
43  dt2txt[(dt, dt_line_num)] += l
44  else:
45  # Corner case, it seems the log's first line can be without
46  # timestamp
47  of.write(l)
48  line_num += 1
49 
50  # Rewrite it in order
51  for dt, dt_line_num in sorted(dt2txt.keys()):
52  of.write(dt2txt[(dt, dt_line_num)])
def datetime_from_str
Definition: reorder_log.py:10