Advertisement
Guest User

ColoredLogcat - Updated

a guest
Jun 16th, 2014
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.50 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. '''
  4.    Copyright 2009, The Android Open Source Project
  5.  
  6.    Licensed under the Apache License, Version 2.0 (the "License");
  7.    you may not use this file except in compliance with the License.
  8.    You may obtain a copy of the License at
  9.  
  10.        http://www.apache.org/licenses/LICENSE-2.0
  11.  
  12.    Unless required by applicable law or agreed to in writing, software
  13.    distributed under the License is distributed on an "AS IS" BASIS,
  14.    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15.    See the License for the specific language governing permissions and
  16.    limitations under the License.
  17. '''
  18.  
  19. # script to highlight adb logcat output for console
  20. # written by jeff sharkey, http://jsharkey.org/
  21. # piping detection and popen() added by other android team members
  22.  
  23.  
  24. import os, sys, re, StringIO
  25. import fcntl, termios, struct
  26. import time
  27. from datetime import datetime
  28.  
  29. # unpack the current terminal width/height
  30. data = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234')
  31. HEIGHT, WIDTH = struct.unpack('hh',data)
  32.  
  33. BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
  34.  
  35. def timestamp():
  36.     now = time.time()
  37.     milliseconds = '%03d' % int((now - int(now)) * 1000)
  38.     return datetime.fromtimestamp(now).strftime('%H:%M:%S') + "." + milliseconds
  39.  
  40. def format(fg=None, bg=None, bright=False, bold=False, dim=False, reset=False):
  41.     # manually derived from http://en.wikipedia.org/wiki/ANSI_escape_code#Codes
  42.     codes = []
  43.     if reset: codes.append("0")
  44.     else:
  45.         if not fg is None: codes.append("3%d" % (fg))
  46.         if not bg is None:
  47.             if not bright: codes.append("4%d" % (bg))
  48.             else: codes.append("10%d" % (bg))
  49.         if bold: codes.append("1")
  50.         elif dim: codes.append("2")
  51.         else: codes.append("22")
  52.     return "\033[%sm" % (";".join(codes))
  53.  
  54.  
  55. def indent_wrap(message, indent=0, width=80):
  56.     wrap_area = width - indent
  57.     messagebuf = StringIO.StringIO()
  58.     current = 0
  59.     while current < len(message):
  60.         next = min(current + wrap_area, len(message))
  61.         messagebuf.write(message[current:next])
  62.         if next < len(message):
  63.             messagebuf.write("\n%s" % (" " * indent))
  64.         current = next
  65.     return messagebuf.getvalue()
  66.  
  67.  
  68. LAST_USED = [RED,GREEN,YELLOW,BLUE,MAGENTA,CYAN,WHITE]
  69. KNOWN_TAGS = {
  70.     "dalvikvm": BLUE,
  71.     "Process": BLUE,
  72.     "ActivityManager": CYAN,
  73.     "ActivityThread": CYAN,
  74. }
  75.  
  76. def allocate_color(tag):
  77.     # this will allocate a unique format for the given tag
  78.     # since we dont have very many colors, we always keep track of the LRU
  79.     if not tag in KNOWN_TAGS:
  80.         KNOWN_TAGS[tag] = LAST_USED[0]
  81.     color = KNOWN_TAGS[tag]
  82.     LAST_USED.remove(color)
  83.     LAST_USED.append(color)
  84.     return color
  85.  
  86.  
  87. RULES = {
  88.     #re.compile(r"([\w\.@]+)=([\w\.@]+)"): r"%s\1%s=%s\2%s" % (format(fg=BLUE), format(fg=GREEN), format(fg=BLUE), format(reset=True)),
  89. }
  90.  
  91. TAGTYPE_WIDTH = 3
  92. TAG_WIDTH = 20
  93. TIME_WIDTH = 11
  94. PROCESS_WIDTH = 8 # 8 or -1
  95. HEADER_SIZE = TAGTYPE_WIDTH + 1 + TIME_WIDTH + 1 + TAG_WIDTH + 1 + PROCESS_WIDTH + 1
  96.  
  97. TAGTYPES = {
  98.     "V": "%s%s%s%s " % (format(fg=WHITE, bg=BLACK), "V".center(TAGTYPE_WIDTH), format(reset=True), format(fg=WHITE)),
  99.     "D": "%s%s%s%s " % (format(fg=BLACK, bg=BLUE), "D".center(TAGTYPE_WIDTH), format(reset=True), format(fg=WHITE)),
  100.     "I": "%s%s%s%s " % (format(fg=BLACK, bg=GREEN), "I".center(TAGTYPE_WIDTH), format(reset=True), format(fg=WHITE)),
  101.     "W": "%s%s%s%s " % (format(fg=BLACK, bg=YELLOW), "W".center(TAGTYPE_WIDTH), format(reset=True), format(fg=YELLOW)),
  102.     "E": "%s%s%s%s " % (format(fg=BLACK, bg=RED), "E".center(TAGTYPE_WIDTH), format(reset=True), format(fg=RED)),
  103.     "F": "%s%s%s%s " % (format(fg=BLACK, bg=RED), "A".center(TAGTYPE_WIDTH), format(reset=True), format(fg=RED)),
  104. }
  105.  
  106. retag = re.compile("^([A-Z])/([^\(]+)\(([^\)]+)\): (.*)$")
  107.  
  108. # to pick up -d or -e
  109. adb_args = ' '.join(sys.argv[1:])
  110.  
  111. # if someone is piping in to us, use stdin as input.  if not, invoke adb logcat
  112. if os.isatty(sys.stdin.fileno()):
  113.     input = os.popen("adb %s logcat" % adb_args)
  114. else:
  115.     input = sys.stdin
  116.  
  117. while True:
  118.     try:
  119.         line = input.readline()
  120.     except KeyboardInterrupt:
  121.         break
  122.  
  123.     match = retag.match(line)
  124.     if not match is None:
  125.         tagtype, tag, owner, message = match.groups()
  126.         linebuf = StringIO.StringIO()
  127.  
  128.         # center process info
  129.         if PROCESS_WIDTH > 0:
  130.             owner = owner.strip().center(PROCESS_WIDTH)
  131.             linebuf.write("%s%s%s " % (format(fg=BLACK, bg=BLACK, bright=True), owner, format(reset=True)))
  132.  
  133.         linebuf.write("%s%s%s" % (format(fg=WHITE), timestamp(), format(reset=True)))
  134.  
  135.         # right-align tag title and allocate color if needed
  136.         tag = tag.strip()
  137.         color = allocate_color(tag)
  138.         tag = tag[-TAG_WIDTH:].rjust(TAG_WIDTH)
  139.         linebuf.write("%s%s %s" % (format(fg=color, dim=False), tag, format(reset=True)))
  140.  
  141.         # write out tagtype colored edge
  142.         if not tagtype in TAGTYPES: break
  143.         linebuf.write(TAGTYPES[tagtype])
  144.  
  145.         # insert line wrapping as needed
  146.         message = indent_wrap(message, HEADER_SIZE, WIDTH)
  147.  
  148.         # format tag message using rules
  149.         for matcher in RULES:
  150.             replace = RULES[matcher]
  151.             message = matcher.sub(replace, message)
  152.  
  153.         linebuf.write(message)
  154.     linebuf.write(format(reset=True))
  155.         line = linebuf.getvalue()
  156.    
  157.     print line
  158.     if len(line) == 0: break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement