2013-10-30 3 views
0

가장 간단한 로거를 원한다면, 대부분 예외를 오류에 단순히 기록하고 싶다면 안드로이드 파일 시스템의 로그 파일에 기록하십시오. 예를 들어, 가장 쉽고 (내 의견으로는) 적어도 PC Java에서 파일에 로그하는 데 사용되는 방법은 모든 예외를 콘솔에 인쇄하고 콘솔과 내 파일 모두로 시스템을 리디렉션하는 것이 었습니다. 안드로이드에 관해서는 안드로이드 OS가 어떻게 설계 되었는가에 대한 이유를 알고 있기 때문에 안드로이드에서 가장 간단한 방법은 무엇일까요?안드로이드 애플 리케이션을위한 파일 로거

프로젝트에 이미 많은 코드가 있으며 실제로 예외를 기록하기 위해 수행해야 할 작업이 거의 없으므로 프로젝트에 이미 많은 코드가 있으며 그걸 검토하고 catch 블록이나 기타 예외를 기록하는 로그 호출을 추가하고 싶습니다. 내 사용 사례 ...

미리 감사드립니다!

답변

0

아직 완성되지 않았지만 안정적으로 작동합니다. 예외 이름, 시간, 스택 추적 및 추가 데이터로 사람이 읽을 수있는 json 배열을 저장합니다. 또한 logcat의 로그를 저장할 수 있습니다.

ExceptionWriter ew = new ExceptionWriter(new File(Environment.getExternalStorageDirectory(), "debug.txt")); 
ew.w(new IllegalArgumentException("some msg"), "additional message"); 

소스 :

import java.io.*; 
import java.text.SimpleDateFormat; 
import java.util.concurrent.ConcurrentLinkedQueue; 

/** 
* User: elevenetc 
* Date: 10/9/13 
* Time: 12:52 PM 
*/ 
public class ExceptionWriter { 

    private final StringBuilder sb; 
    private final ExceptionWriter.WriteExceptionTask writeExceptionTask; 
    private final SimpleDateFormat dataFormat; 
    private int totalExceptions; 
    private StringBuilder stackBuilder = new StringBuilder(); 

    public int getTotalExceptions(){return totalExceptions;} 

    public ExceptionWriter(File file) throws IOException { 
     if(file != null){ 
      writeExceptionTask = new WriteExceptionTask(file); 
      sb = new StringBuilder(); 
      dataFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); 
      new Thread(writeExceptionTask).start(); 
     }else{ 
      sb = null; 
      writeExceptionTask = null; 
      dataFormat = null; 
     } 

    } 

    public synchronized int wLogcat(){ 
     try { 
      writeExceptionTask.addStreamToRead(Runtime.getRuntime().exec("logcat -d -v time").getInputStream()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return 0; 
    } 

    public int w(Exception debugException, String caughtMessage){ 
     return w(debugException, caughtMessage, null); 
    } 

    public synchronized int w(Exception debugException, String caughtMessage, String additionalData){ 

     if(writeExceptionTask == null) return -1; 

     sb.setLength(0); 

     StackTraceElement[] stackTrace = debugException == null ? null : debugException.getStackTrace(); 

     sb.append("{\"date\":\"");sb.append(getTime()); 
     sb.append("\",\"exceptionClassName\":\"");sb.append(debugException == null ? null : debugException.getClass()); 
     sb.append("\",\"exceptionMessage:\":\"");sb.append(debugException == null ? null : debugException.getMessage()); 
     sb.append("\",\"caughtMessage:\":\"");sb.append(caughtMessage); 
     if(additionalData != null) {sb.append("\",\"data:\":\"");sb.append(additionalData);} 
     sb.append("\",\"stack\":");sb.append(stackToString(stackTrace)); 
     sb.append("},"); 

     writeExceptionTask.stringQueue.add(sb.toString()); 

     totalExceptions++; 

     return 0; 
    } 

    public void destroy() { 
     if(writeExceptionTask != null) { 
      writeExceptionTask.stop(); 
     } 
    } 

    private String getTime(){ 
     return dataFormat.format(System.currentTimeMillis()); 
    } 

    private String stackToString(StackTraceElement[] stackTrace){ 

     if(stackTrace == null) return null; 

     stackBuilder.setLength(0); 

     stackBuilder.append("["); 
     for (int i = 0; i < stackTrace.length; i++) { 
      StackTraceElement e = stackTrace[i]; 

      stackBuilder.append("{\""); 
      stackBuilder.append(e.getLineNumber()); 
      stackBuilder.append("\":\""); 
      stackBuilder.append(e.getClassName()); 
      stackBuilder.append("."); 
      stackBuilder.append(e.getMethodName()); 
      stackBuilder.append("\"}"); 

      if(i != stackTrace.length -1) stackBuilder.append(","); 
     } 
     stackBuilder.append("]"); 
     return stackBuilder.toString(); 
    } 

    /////////////////////////////////////////////// 
    /// Static classes 
    /////////////////////////////////////////////// 

    private class WriteExceptionTask implements Runnable { 

     private final File file; 
     private boolean running; 
     private final ConcurrentLinkedQueue<String> stringQueue; 
     private final ConcurrentLinkedQueue<InputStream> isQueue; 
     private final FileWriter writer; 

     private WriteExceptionTask(File file) throws IOException { 
      this.file = file; 
      writer = new FileWriter(this.file, true); 
      stringQueue = new ConcurrentLinkedQueue<String>(); 
      isQueue = new ConcurrentLinkedQueue<InputStream>(); 
      running = true; 
     } 

     public void addStreamToRead(InputStream is){ 
      if(is != null){ 
       isQueue.add(is); 
      } 
     } 

     @Override 
     public void run() { 
      while(running){ 
       if(!stringQueue.isEmpty()){ 

        //TODO check file existence 

        try { 
         writer.append(stringQueue.poll()); 
         writer.flush(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
         running = false; 
        } 
       } 

       if(!isQueue.isEmpty()){ 
        InputStream is = isQueue.poll(); 
        BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 

        StringBuilder builder = new StringBuilder("{\"catLog\":\""); 

        String aux; 

        try { 

         while ((aux = reader.readLine()) != null) { 
          //TODO view like array or \n 
          builder.append(aux); 
         } 

        } catch (IOException e) { 
         e.printStackTrace(); 
        } 

        builder.append("\"},"); 

        stringQueue.add(builder.toString()); 
       } 
      } 

      try { 
       writer.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

     public void stop() { 
      running = false; 
     } 
    } 

} 
를 사용

관련 문제