扩展Android.util.Log以写入文件

时间:2013-09-10 08:29:09

标签: android logging android-logcat

我想扩展android.util.Log类,以便写入设备内部存储中的日志文件,最好还是特定的TAGS

我目前有一个实现:

public class CustomLogger{

private final static Logger fileLog = Logger.getLogger(MainActivity.class);
private Context context;

public CustomLogger(Context c){
    this.context = c;

    final LogConfigurator logConfigurator = new LogConfigurator();
    logConfigurator.setFileName(context.getFilesDir() + File.separator + "myApp.log");
    logConfigurator.setRootLevel(Level.DEBUG);
    logConfigurator.setLevel("org.apache", Level.ERROR);
    logConfigurator.configure();
}

public void i(String TAG, String message){

    // Printing the message to LogCat console
    Log.i(TAG, message);

    // Write the log message to the file
    fileLog.info(TAG+": "+message);
}

public void d(String TAG, String message){
    Log.d(TAG, message);
    fileLog.debug(TAG+": "+message);
  }
 } 

如您所见,此自定义记录器将两者记录到内部存储上的日志文件(使用android-logging-log4j库)和android.util.Log类。 但是,我希望我的日志文件中android.util.Log类的标准日志条目,如果可能,只需要某些(自定义)TAGS

任何人都有关于如何达到此目的的示例或任何好的提示?

提前致谢

2 个答案:

答案 0 :(得分:7)

您可以通过编程方式阅读log cat并将其存储到文本文件中,或者将其发送到任何您想要的地方。

下面是我为同一篇文章撰写的详细文章

Read & Store Log-cat Programmatically in Android

并且在这里阅读logcat是示例代码

    public class LogTest extends Activity {

 private StringBuilder log;

 @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()));

    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) {
  }       


 //convert log to string
 final String logString = new String(log.toString());

 //create text file in SDCard
 File sdCard = Environment.getExternalStorageDirectory();
 File dir = new File (sdCard.getAbsolutePath() + "/myLogcat");
 dir.mkdirs();
 File file = new File(dir, "logcat.txt");

 try {  
  //to write logcat in text file
  FileOutputStream fOut = new FileOutputStream(file);
  OutputStreamWriter osw = new OutputStreamWriter(fOut); 

        // Write the string to the file
        osw.write(logString);            
        osw.flush();
        osw.close();
 } catch (FileNotFoundException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 }
  }
}

答案 1 :(得分:1)

因此有更短的变体

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