2012-06-26 6 views
3

Android 기기에서 logcat을 가져 오려면 adb shell logcat (일부 grep 필터링 포함)을 사용하십시오. 다음과 같이색상의 adb logcat in Ubuntu 명령 행

예 출력은 다음과 같습니다

E/com.samsung.app(3739): [MSC]>>>... 
I/InputDispatcher(2882): Delivering ... 
D/ProgramMonitor(3770): START ... 
D/ProgramMonitor(3770): LAUNCHER_RESUME... 
I/Debug (3815): onReceive... 
E/Debug (3815): receive ... 
D/ClientReporter(3036): ... 

내 질문은 내가 로그의 첫 글자에 따라 출력의 색상을 변경하는 방법입니다. 그래서 "E"는 빨간색으로, "D"는 녹색으로, 등등 ... 이클립스에서 로그가 보이는 것과 비슷합니다. 그것은 사용하기 원하는 경우 수정하는 정말 쉽습니다

Modifying the Android logcat stream for full-color debugging

:

답변

7

내가 여기 파이썬 스크립트를 사용하여 감사드립니다.

완전한 소스 코드 : 당신은 NPM이있는 경우

#!/usr/bin/python 

''' 
    Copyright 2009, The Android Open Source Project 

    Licensed under the Apache License, Version 2.0 (the "License"); 
    you may not use this file except in compliance with the License. 
    You may obtain a copy of the License at 

     http://www.apache.org/licenses/LICENSE-2.0 

    Unless required by applicable law or agreed to in writing, software 
    distributed under the License is distributed on an "AS IS" BASIS, 
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
    See the License for the specific language governing permissions and 
    limitations under the License. 
''' 

# script to highlight adb logcat output for console 
# written by jeff sharkey, http://jsharkey.org/ 
# piping detection and popen() added by other android team members 


import os, sys, re, StringIO 
import fcntl, termios, struct 

# unpack the current terminal width/height 
data = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234') 
HEIGHT, WIDTH = struct.unpack('hh',data) 

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) 

def format(fg=None, bg=None, bright=False, bold=False, dim=False, reset=False): 
    # manually derived from http://en.wikipedia.org/wiki/ANSI_escape_code#Codes 
    codes = [] 
    if reset: codes.append("0") 
    else: 
     if not fg is None: codes.append("3%d" % (fg)) 
     if not bg is None: 
      if not bright: codes.append("4%d" % (bg)) 
      else: codes.append("10%d" % (bg)) 
     if bold: codes.append("1") 
     elif dim: codes.append("2") 
     else: codes.append("22") 
    return "\033[%sm" % (";".join(codes)) 


def indent_wrap(message, indent=0, width=80): 
    wrap_area = width - indent 
    messagebuf = StringIO.StringIO() 
    current = 0 
    while current < len(message): 
     next = min(current + wrap_area, len(message)) 
     messagebuf.write(message[current:next]) 
     if next < len(message): 
      messagebuf.write("\n%s" % (" " * indent)) 
     current = next 
    return messagebuf.getvalue() 


LAST_USED = [RED,GREEN,YELLOW,BLUE,MAGENTA,CYAN,WHITE] 
KNOWN_TAGS = { 
    "dalvikvm": BLUE, 
    "Process": BLUE, 
    "ActivityManager": CYAN, 
    "ActivityThread": CYAN, 
} 

def allocate_color(tag): 
    # this will allocate a unique format for the given tag 
    # since we dont have very many colors, we always keep track of the LRU 
    if not tag in KNOWN_TAGS: 
     KNOWN_TAGS[tag] = LAST_USED[0] 
    color = KNOWN_TAGS[tag] 
    LAST_USED.remove(color) 
    LAST_USED.append(color) 
    return color 


RULES = { 
    #re.compile(r"([\w\[email protected]]+)=([\w\[email protected]]+)"): r"%s\1%s=%s\2%s" % (format(fg=BLUE), format(fg=GREEN), format(fg=BLUE), format(reset=True)), 
} 

TAGTYPE_WIDTH = 3 
TAG_WIDTH = 20 
PROCESS_WIDTH = 8 # 8 or -1 
HEADER_SIZE = TAGTYPE_WIDTH + 1 + TAG_WIDTH + 1 + PROCESS_WIDTH + 1 

TAGTYPES = { 
    "V": "%s%s%s " % (format(fg=WHITE, bg=BLACK), "V".center(TAGTYPE_WIDTH), format(reset=True)), 
    "D": "%s%s%s " % (format(fg=BLACK, bg=BLUE), "D".center(TAGTYPE_WIDTH), format(reset=True)), 
    "I": "%s%s%s " % (format(fg=BLACK, bg=GREEN), "I".center(TAGTYPE_WIDTH), format(reset=True)), 
    "W": "%s%s%s " % (format(fg=BLACK, bg=YELLOW), "W".center(TAGTYPE_WIDTH), format(reset=True)), 
    "E": "%s%s%s " % (format(fg=BLACK, bg=RED), "E".center(TAGTYPE_WIDTH), format(reset=True)), 
} 

retag = re.compile("^([A-Z])/([^\(]+)\(([^\)]+)\): (.*)$") 

# to pick up -d or -e 
adb_args = ' '.join(sys.argv[1:]) 

# if someone is piping in to us, use stdin as input. if not, invoke adb logcat 
if os.isatty(sys.stdin.fileno()): 
    input = os.popen("adb %s logcat" % adb_args) 
else: 
    input = sys.stdin 

while True: 
    try: 
     line = input.readline() 
    except KeyboardInterrupt: 
     break 

    match = retag.match(line) 
    if not match is None: 
     tagtype, tag, owner, message = match.groups() 
     linebuf = StringIO.StringIO() 

     # center process info 
     if PROCESS_WIDTH > 0: 
      owner = owner.strip().center(PROCESS_WIDTH) 
      linebuf.write("%s%s%s " % (format(fg=BLACK, bg=BLACK, bright=True), owner, format(reset=True))) 

     # right-align tag title and allocate color if needed 
     tag = tag.strip() 
     color = allocate_color(tag) 
     tag = tag[-TAG_WIDTH:].rjust(TAG_WIDTH) 
     linebuf.write("%s%s %s" % (format(fg=color, dim=False), tag, format(reset=True))) 

     # write out tagtype colored edge 
     if not tagtype in TAGTYPES: break 
     linebuf.write(TAGTYPES[tagtype]) 

     # insert line wrapping as needed 
     message = indent_wrap(message, HEADER_SIZE, WIDTH) 

     # format tag message using rules 
     for matcher in RULES: 
      replace = RULES[matcher] 
      message = matcher.sub(replace, message) 

     linebuf.write(message) 
     line = linebuf.getvalue() 

    print line 
    if len(line) == 0: break 
+0

감사합니다. 그것은 매우 도움이되었다! – MobileCushion

+0

이 유틸리티는 마음에 들지만 실제로는 라인 자체에서 색상 코딩을 그리워합니다. 색상을 사용하여 중요한 흐름을 추적합니다 :-) 필자는 파이썬이 null이라는 것을 추가해야합니다. –

+0

터미널이나 글꼴을 설정해야합니까? 간격을두고 녹색 텍스트가 계속 표시됩니다. –

2

, 당신이 모듈을 설치할 수 있습니다 : 당신을 제공 할 것입니다

$ npm install -g logcat 

는 콘솔에 색깔 로그 캣 모니터링을 시작 //127.0.0.1/ .

$ logcat 

Here 내가 죽은 간단한 무언가를 원하고 분석하고 출력을 포맷 어떤 거대한 스크립트를 가져 오지 않았다, 그래서 나는이 함께했다 설명

+0

당신의 의도는 아마 좋은데, 이것은 "빌드"가 의존성을 가져 오지 못하기 때문에 (의존성이 많이) 최근 Ubuntu에서는 작동하지 않습니다. 나는 Python 스크립트가 더 좋으며, 대부분의 배포판에 이미 설치된 Python 만 필요하기 때문에. – wojciii

0

입니다. 이것은 문자 그대로 입력 라인을 정확하게 출력하고 그에 따라 색상 코드를 추가합니다. 이 표준 -v time 형식에서 작동하지만, 물론 당신이 원하는대로 형식에 맞게 수정 될 수 있음을

#!/usr/bin/env python 

import sys 
import subprocess 
import csv 

DEFAULT = "0;37;49" 
ERROR = "0;91;49" 
WARNING = "0;93;49" 
INFO = "0;92;49" 
DEBUG = "0;94;49" 
VERBOSE = "0;97;49" 

try: 
    proc = subprocess.Popen(['adb','logcat', '-v', 'time'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
    for line in iter(proc.stdout.readline, ''): 
     l = line.split(None, 3) 
     try: 
      level_and_tag = l[2] 

      if level_and_tag.startswith('E/'): color = ERROR 
      elif level_and_tag.startswith('W/'): color = WARNING 
      elif level_and_tag.startswith('I/'): color = INFO 
      elif level_and_tag.startswith('D/'): color = DEBUG 
      elif level_and_tag.startswith('V/'): color = VERBOSE 
      else: color = DEFAULT 
     except IndexError as e: 
      color = DEFAULT 

     print '\x1b[%sm %s \x1b[0m' % (color, line.strip()) 
     #sys.stdout.write('\x1b[%sm %s \x1b[0m' % (color, line)) 
except KeyboardInterrupt: 
    # Make sure color gets set back to terminal default 
    print '\x1b[%sm %s \x1b[0m' % (DEFAULT, ">>> Exit") 

참고.