-
Notifications
You must be signed in to change notification settings - Fork 1
/
colorize
executable file
·79 lines (63 loc) · 1.85 KB
/
colorize
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
#!/usr/bin/env python
#
# Author: Todd Lipcon
# From https://github.com/toddlipcon/tlipcon-bin
#
# Usage:
# grep blk_2015554029480362352_ * | perl -p -e
# 's,hadoop-cmf-hdfs1-DATANODE-hdpr([0-9]+).log.out.2012-04-09,node-\1,'
# | sort -t ' ' -k2 | colorize "{'blk_\d+': 'red',
# 'wildcard.*':'bold,yellow', 'node-001':'blue',
# 'node-009':'white','node-010':'purple', '1982508':'white',
# '1982421':'yellow'}" | less -RS
# (less -R is required for paging through text which has ansi escape
# sequences like this)
#
# I also use a "colorize-log" alias a lot for HDFS:
# colorize "{r'WARN|FATAL|Exception': 'red', r'blk_\d+': 'yellow'}
#
import sys
import re
from optparse import OptionParser
COLORS = {
'bold': '\033[1m',
'italic': '\033[3m',
'underline': '\033[4m',
'inverse': '\033[7m',
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': "\033[34m",
'purple': "\033[35m",
'lightblue': "\033[36m",
'white': "\033[37m",
'redbg': '\033[41m',
'greenbg': '\033[42m',
'yellowbg': '\033[43m',
'bluebg': "\033[44m",
'purplebg': "\033[45m",
'lightbluebg': "\033[46m",
'whitebg': "\033[47m",
'end': "\033[0m"
}
parser = OptionParser()
parser.add_option("-o", "--only-colored-lines", dest="only_colored", action="store_true")
parser.usage = "%s <color hash>"
options, args = parser.parse_args()
if len(args) != 1:
options.print_help(sys.stderr)
sys.exit(1)
colors = eval(args[0])
def make_repl(color):
parts = color.split(",")
return ("".join(COLORS[part.strip()] for part in parts) +
r'\g<0>' + COLORS['end'])
pairs = [(re.compile(regex), make_repl(colorspec))
for regex,colorspec in colors.iteritems()]
for line in sys.stdin.xreadlines():
made_sub = 0
for r, repl in pairs:
line,count = re.subn(r, repl, line)
made_sub += count
if not options.only_colored or made_sub > 0:
print line,