-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog-frequency.py
More file actions
executable file
·55 lines (45 loc) · 1.64 KB
/
Copy pathlog-frequency.py
File metadata and controls
executable file
·55 lines (45 loc) · 1.64 KB
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
#!/usr/bin/env python3
"""Count frequent log messages or regular-expression capture groups."""
import argparse
import re
import sys
from collections import Counter
from pathlib import Path
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("files", nargs="*", type=Path, help="Log files; stdin when omitted")
parser.add_argument("--regex", help="Only matching lines; first capture group becomes the key")
parser.add_argument("--top", type=int, default=20)
parser.add_argument("--normalize-numbers", action="store_true")
parser.add_argument("--ignore-case", action="store_true")
return parser.parse_args()
def lines(files):
if not files:
yield from sys.stdin
return
for path in files:
with path.open(encoding="utf-8", errors="replace") as handle:
yield from handle
def main():
args = parse_args()
if args.top < 1:
raise SystemExit("--top must be positive")
pattern = re.compile(args.regex, re.IGNORECASE if args.ignore_case else 0) if args.regex else None
counts = Counter()
for line in lines(args.files):
key = line.strip()
if pattern:
match = pattern.search(key)
if not match:
continue
key = match.group(1) if match.groups() else match.group(0)
if args.normalize_numbers:
key = re.sub(r"\b\d+\b", "<N>", key)
if args.ignore_case:
key = key.lower()
if key:
counts[key] += 1
for key, count in counts.most_common(args.top):
print(f"{count}\t{key}")
if __name__ == "__main__":
main()