source: ntrip/trunk/BNC/tests/tools/logcheck.py

Last change on this file was 11193, checked in by stuerze, 2 weeks ago

Structured logging improved

File size: 6.8 KB
Line 
1#!/usr/bin/env python3
2"""Consistency check of BNC's structured logfile (option logFileStructured)
3
4 logcheck.py CLASSIC_LOG JSON_LOG [LOGFMT_LOG]
5
6Checks that every line of the JSON file is a JSON object and every line of the
7logfmt file a sequence of key=value pairs, that both carry the same records,
8that the records have the mandatory keys in the documented order (optional
9'epoch' after 'time', GPS Time without 'Z'), that the records belong line by
10line to the classic logfile ('msg' is the classic text without the "<mp>: "
11prefix and trailing blanks, shortened for events whose fields carry the details, see matches();
12classic lines without their "yy-mm-dd hh:mm:ss " prefix; the start line is
13skipped, it goes to the file of the current date) and that 'time' (UTC) is the
14GPS Time stamp of the classic line minus the GPS-UTC leap seconds. Prints a
15summary of the records per level, component and event; exit code 1 on any
16error.
17"""
18
19import collections
20import datetime
21import json
22import re
23import sys
24
25HEAD = ["time", "level", "component", "event"]
26LEVELS = {"info", "warning", "error"}
27LEAP_GPS_UTC = 18 # valid since 2017-01-01
28
29
30def parse_logfmt(line):
31 rec, i, n = {}, 0, len(line)
32 while i < n:
33 j = line.index("=", i)
34 key = line[i:j]
35 i = j + 1
36 if i < n and line[i] == '"':
37 i += 1
38 val = []
39 while line[i] != '"':
40 if line[i] == "\\":
41 i += 1
42 val.append({"n": "\n", "r": "\r", "t": "\t"}.get(line[i], line[i]))
43 if line[i] == "u":
44 val[-1] = chr(int(line[i + 1:i + 5], 16))
45 i += 4
46 else:
47 val.append(line[i])
48 i += 1
49 i += 1
50 rec[key] = "".join(val)
51 else:
52 j = line.find(" ", i)
53 j = n if j < 0 else j
54 raw = line[i:j]
55 i = j
56 if raw in ("true", "false"):
57 rec[key] = raw == "true"
58 elif raw == "null":
59 rec[key] = None
60 elif re.fullmatch(r"-?\d+", raw):
61 rec[key] = int(raw)
62 elif re.fullmatch(r"-?\d+\.\d*", raw):
63 rec[key] = float(raw)
64 else:
65 rec[key] = raw
66 if i < n:
67 if line[i] != " ":
68 raise ValueError("blank expected at %d" % i)
69 i += 1
70 return rec
71
72
73# events with a short structured 'msg': prefix the classic line must start with
74SHORT = {
75 "ppp_position": lambda r: "%s %s X = " % (r["epoch"].replace("T", "_"), r["mp"]),
76 "stream_latency": lambda r: "%s %s: Mean latency " % (r["mp"], r["type"]),
77}
78
79SHORT_MSG = {"ppp_position": "PPP position", "stream_latency": "Latency"}
80
81
82def matches(r, line):
83 """Does the record belong to the classic logfile line? The structured 'msg'
84 is the classic text without the "<mp>: " prefix, shortened where the
85 fields carry the details."""
86 mp, msg, ev = r.get("mp"), r.get("msg"), r.get("event")
87 if ev in SHORT:
88 return msg == SHORT_MSG[ev] and line.startswith(SHORT[ev](r))
89 if ev == "stream_content" and msg == "Received RTCM message":
90 size = " (size %d)" % r["size"] if "size" in r else " "
91 return line == "%s: Received message type %d%s" % (mp, r["message_type"], size)
92 if mp and line.startswith(mp + ": "):
93 line = line[len(mp) + 2:]
94 line = line.rstrip(" ")
95 if ev.startswith("stream_outage_") or ev.startswith("stream_corrupted_"):
96 return line.startswith(msg + " ")
97 return msg == line
98
99
100def main():
101 errors = []
102 classic, stamps = [], []
103 for line in open(sys.argv[1], encoding="latin-1", newline="").read().split("\r\n"):
104 if not line or "========== Start BNC" in line:
105 continue
106 if re.match(r"\d\d-\d\d-\d\d \d\d:\d\d:\d\d ", line):
107 classic.append(line[18:])
108 stamps.append(datetime.datetime.strptime(line[:17], "%y-%m-%d %H:%M:%S"))
109 else:
110 classic.append(line)
111 stamps.append(None)
112
113 recs = []
114 for k, line in enumerate(open(sys.argv[2], encoding="utf-8"), 1):
115 try:
116 recs.append(json.loads(line, object_pairs_hook=collections.OrderedDict))
117 except ValueError as e:
118 errors.append("json line %d: %s" % (k, e))
119 if len(sys.argv) > 3:
120 lf = []
121 for k, line in enumerate(open(sys.argv[3], encoding="utf-8"), 1):
122 try:
123 lf.append(parse_logfmt(line.rstrip("\n")))
124 except (ValueError, IndexError) as e:
125 errors.append("logfmt line %d: %s" % (k, e))
126 if len(lf) != len(recs):
127 errors.append("json %d records, logfmt %d" % (len(recs), len(lf)))
128 for k, (a, b) in enumerate(zip(recs, lf), 1):
129 # the start line carries the wall clock time of each run
130 start = "========== Start BNC" in a.get("msg", "")
131 if list(a.keys()) != list(b.keys()) or any(a[x] != b[x] for x in a
132 if not (start and x == "time")):
133 errors.append("record %d differs between json and logfmt" % k)
134
135 count = collections.Counter()
136 for k, r in enumerate(recs, 1):
137 keys = list(r.keys())
138 if keys[1:2] == ["epoch"]:
139 try:
140 datetime.datetime.strptime(r["epoch"], "%Y-%m-%dT%H:%M:%S.%f")
141 except ValueError:
142 errors.append("record %d: epoch %s" % (k, r["epoch"]))
143 keys = keys[:1] + keys[2:]
144 if keys[:4] != HEAD or keys[-2:] != ["msg", "v"]:
145 errors.append("record %d: keys %s" % (k, keys))
146 continue
147 if r["level"] not in LEVELS:
148 errors.append("record %d: level %s" % (k, r["level"]))
149 count[(r["level"], r["component"], r["event"])] += 1
150
151 body = [r for r in recs if "========== Start BNC" not in r.get("msg", "")]
152 for k, (r, st) in enumerate(zip(body, stamps), 1):
153 utc = datetime.datetime.strptime(r["time"], "%Y-%m-%dT%H:%M:%S.%fZ")
154 if st is not None and (st - utc.replace(microsecond=0)).total_seconds() != LEAP_GPS_UTC:
155 errors.append("record %d: time %s, classic %s" % (k, r["time"], st))
156 for k, (r, line) in enumerate(zip(body, classic), 1):
157 if not matches(r, line):
158 errors.append("record %d: msg %r, classic %r" % (k, r.get("msg"), line))
159 break
160 if len(body) != len(classic):
161 errors.append("%d records, %d classic lines" % (len(body), len(classic)))
162
163 print("%d records" % len(recs))
164 for (lev, comp, ev), n in sorted(count.items()):
165 print("%6d %-8s %-8s %s" % (n, lev, comp, ev))
166 for e in errors:
167 print("ERROR", e)
168 print("OK" if not errors else "%d error(s)" % len(errors))
169 return 1 if errors else 0
170
171
172if __name__ == "__main__":
173 sys.exit(main())
Note: See TracBrowser for help on using the repository browser.