forked from algorand/go-algorand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjslog
executable file
·159 lines (147 loc) · 4.75 KB
/
jslog
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#!/usr/bin/env python3
# -*- python -*-
#
# Read algod json logs and format them pretty.
# Can filter on some of the fields.
#
# requires termcolor:
# pip install termcolor
import datetime
import json
import re
import sys
import time
from termcolor import colored
level_short = {
'debug': colored('D', 'grey'),
'info': 'I',
'warn': colored('W', 'yellow'),
'warning': colored('W', 'yellow'),
'error': colored('E', 'red'),
}
level_num = {
'debug':0,
'info':1,
'warn':2,
'warning':2,
'error':3,
}
def levelToNum(x):
l = level_num.get(x)
if l is None:
try:
return int(l)
except:
return -1
return l
def dictfilter(d):
out = dict()
for k,v in d.items():
if not k or not v:
continue
out[k] = v
return out
class LogFile:
def __init__(self):
self.fileRe = None
self.messageRe = None
self.levelMin = 0
self.levelAlways = 2
self.functionPrefixRemovals = ['github.com/algorand/go-algorand/']
def recordGenerator(self, fin):
for line in fin:
if not line:
continue
line = line.strip()
if not line:
continue
if line[0] == '#':
continue
try:
ob = json.loads(line)
yield ob
except:
sys.stderr.write(line + '\n')
def format(self, rec):
# e.g.
# {"file":"wsNetwork.go","function":"github.com/algorand/go-algorand/network.(*WebsocketNetwork).readFromBootstrap","level":"debug","line":682,"msg":"no dns lookup due to empty bootstrapID","name":"127.0.0.1:0","time":"2019-02-01T13:03:35-05:00"}
level = rec.pop('level', None)
fname = rec.pop('file', None)
fline = rec.pop('line', None)
function = rec.pop('function', '')
msg = rec.pop('msg', None)
when = rec.pop('time', None)
go = False
lnum = levelToNum(level)
if lnum < self.levelMin:
print('level {} -> {}'.format(level, lnum))
return None
if lnum > self.levelAlways:
go = True
if not go and not self.fileRe and not self.messageRe:
go = True
if not go and self.fileRe and self.fileRe.search(fname):
go = True
if not go and self.messageRe and self.messageRe.search(msg):
go = True
if not go:
return None
if when:
when = datetime.datetime.strptime(when, '%Y-%m-%dT%H:%M:%S%z')
now = time.time()
dt = when.timestamp() - now
# TODO: format sub-second if available
if dt < 3600:
ds = time.strftime('%H:%M:%S', time.gmtime(when.timestamp()))
elif dt < 3600 * 24:
ds = time.strftime('%H:%M:%S', time.gmtime(when.timestamp()))
elif dt < 3600 * 24 * 7:
ds = time.strftime('%d %H:%M:%S', time.gmtime(when.timestamp()))
else:
ds = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(when.timestamp()))
ds = colored(ds, 'red')
else:
ds = ' '
if fname or fline:
fs = colored('{}:{} '.format(fname, fline), 'blue')
else:
fs = ' '
ls = level_short.get(level, level)
if function:
function = ' ' + colored(self.functionCleanup(function), 'green')
rest = ''
rec = dictfilter(rec)
if rec:
rest = ' ' + repr(rec)
return (ds + ls + fs + msg + function + rest)
def read(self, fin):
for rec in self.recordGenerator(fin):
formatted = self.format(rec)
if formatted is not None:
print(formatted)
def functionCleanup(self, f):
for prefix in self.functionPrefixRemovals:
f = f.replace(prefix, '')
return f
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-f', '--file', help='regex applied to file name')
ap.add_argument('-g', '--msg', help='regex applied to message')
ap.add_argument('-m', '--min', help='minimum log level to display')
ap.add_argument('-L', '--always', help='log level to ALWAYS display, even if it misses other regexes')
# TODO: --follow for `tail -f` behavior
# TODO: time based filtering, e.g. newer than 5 minutes ago
args = ap.parse_args()
lf = LogFile()
if args.file:
lf.fileRe = re.compile(args.file, re.IGNORECASE)
if args.msg:
lf.messageRe = re.compile(args.msg, re.IGNORECASE)
if args.min:
lf.levelMin = levelToNum(args.min)
if args.always:
lf.levelAlways = levelToNum(args.always)
lf.read(sys.stdin)
if __name__ == '__main__':
main()