Program Club

Android logcat 데이터를 파일에 쓰기

proclub 2020. 11. 3. 19:28
반응형

Android logcat 데이터를 파일에 쓰기


사용자가 로그를 수집하고 싶을 때마다 Android logcat을 파일에 덤프하고 싶습니다. adb 도구를 통해를 사용하여 로그를 파일로 리디렉션 할 수 adb logcat -f filename있지만 프로그래밍 방식으로 어떻게 할 수 있습니까?


다음은 로그를 읽는 입니다.

대신 파일에 쓰도록 변경할 수 있습니다 TextView.

다음에서 허가 필요 AndroidManifest:

<uses-permission android:name="android.permission.READ_LOGS" />

암호:

public class LogTest extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try {
      Process process = Runtime.getRuntime().exec("logcat -d");
      BufferedReader bufferedReader = new BufferedReader(
      new InputStreamReader(process.getInputStream()));

      StringBuilder log = new StringBuilder();
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        log.append(line);
      }
      TextView tv = (TextView) findViewById(R.id.textView1);
      tv.setText(log.toString());
    } catch (IOException e) {
    }
  }
}

Logcat은 파일에 직접 쓸 수 있습니다.

public static void saveLogcatToFile(Context context) {    
    String fileName = "logcat_"+System.currentTimeMillis()+".txt";
    File outputFile = new File(context.getExternalCacheDir(),fileName);
    @SuppressWarnings("unused")
    Process process = Runtime.getRuntime().exec("logcat -f "+outputFile.getAbsolutePath());
}

logcat에 대한 자세한 정보 : http://developer.android.com/tools/debugging/debugging-log.html 참조


또는이 변형을 시도 할 수 있습니다.

{
    최종 파일 경로 = new File (
            Environment.getExternalStorageDirectory (), "DBO_logs5");
    if (! path.exists ()) {
        path.mkdir ();
    }
    Runtime.getRuntime (). exec (
            "logcat -d -f"+ 경로 + File.separator
                    + "dbo_logcat"
                    + ".txt");
} catch (IOException e) {
    e.printStackTrace ();
}

public static void writeLogToFile(Context context) {    
    String fileName = "logcat.txt";
    File file= new File(context.getExternalCacheDir(),fileName);
    if(!file.exists())
         file.createNewFile();
    String command = "logcat -f "+file.getAbsolutePath();
    Runtime.getRuntime().exec(command);
}

위의 방법은 모든 로그를 파일에 기록합니다. 또한 매니페스트 파일에 아래 권한을 추가하십시오

<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

참고 URL : https://stackoverflow.com/questions/6175002/write-android-logcat-data-to-a-file

반응형