blob: 2e7bbb543974db032e2c2742cef3061574ac2383 [file] [log] [blame]
Patrick Williamsb8c5eae2022-12-05 14:35:02 -06001#!/usr/bin/env python3
Andrew Geissler19672b62018-02-07 12:33:02 -06002
3r"""
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06004BMC FFDC will at times include the journal in json format
Andrew Geissler19672b62018-02-07 12:33:02 -06005(journalctl -o json-pretty ). This is a quick and dirty script which
6will convert that json output into the standard journalctl output
7"""
8
Manojkiran Edac17b4382025-06-10 11:22:04 +05309import datetime
Andrew Geissler19672b62018-02-07 12:33:02 -060010import json
11import re
Andrew Geissler19672b62018-02-07 12:33:02 -060012from argparse import ArgumentParser
Manojkiran Edac17b4382025-06-10 11:22:04 +053013from datetime import timezone
Andrew Geissler19672b62018-02-07 12:33:02 -060014
Andrew Geissler964ae7b2018-11-14 12:30:01 -060015
Andrew Geissler19672b62018-02-07 12:33:02 -060016def jpretty_to_python(buf):
17 entries = []
18
Patrick Williamsb8c5eae2022-12-05 14:35:02 -060019 for entry in re.findall("^{$(.+?)^}$", buf, re.DOTALL | re.MULTILINE):
20 entries += [json.loads("{{{}}}".format(entry))]
Andrew Geissler19672b62018-02-07 12:33:02 -060021
22 return entries
23
Andrew Geissler964ae7b2018-11-14 12:30:01 -060024
Manojkiran Edac17b4382025-06-10 11:22:04 +053025def format_timestamp_utc(us_timestamp, use_utc=False):
26 """Convert microseconds since epoch to formatted timestamp (with microseconds)."""
27 ts = float(us_timestamp) / 1000000
28 tz = timezone.utc if use_utc else None
29 dt = datetime.datetime.fromtimestamp(ts, tz)
30 return dt.strftime("%b %d %H:%M:%S.%f")
31
32
Patrick Williamsb8c5eae2022-12-05 14:35:02 -060033if __name__ == "__main__":
Andrew Geissler19672b62018-02-07 12:33:02 -060034 parser = ArgumentParser()
35 parser.add_argument(
Patrick Williamsb8c5eae2022-12-05 14:35:02 -060036 "journalfile", metavar="FILE", help="the file to parse"
37 )
Manojkiran Edac17b4382025-06-10 11:22:04 +053038 parser.add_argument(
39 "--localtime",
40 action="store_true",
41 help="Display timestamps in local time (default is UTC)",
42 )
Andrew Geissler19672b62018-02-07 12:33:02 -060043 args = parser.parse_args()
44
45 with open(args.journalfile) as fd:
46 entries = jpretty_to_python(fd.read())
Patrick Williamsb8c5eae2022-12-05 14:35:02 -060047 entries = sorted(entries, key=lambda k: k["__REALTIME_TIMESTAMP"])
Andrew Geissler19672b62018-02-07 12:33:02 -060048
49 for e in entries:
Manojkiran Edac17b4382025-06-10 11:22:04 +053050 e["ts"] = format_timestamp_utc(
51 e["__REALTIME_TIMESTAMP"], use_utc=not args.localtime
52 )
Andrew Geissler964ae7b2018-11-14 12:30:01 -060053 try:
Patrick Williamsb8c5eae2022-12-05 14:35:02 -060054 print(
55 f'{e["ts"]} {e["_HOSTNAME"]} {e["SYSLOG_IDENTIFIER"]}:'
56 f' {e["MESSAGE"]}'
57 )
58 except Exception:
59 print("Unable to parse msg: " + str(e))
Andrew Geissler964ae7b2018-11-14 12:30:01 -060060 continue