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

我想扩展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); } } 

正如你所看到的,这个自定义logging器既logging到内部存储器上的日志文件(使用android-logging-log4j库),也通过android.util.Log类logging。 不过,我想从我的日志文件中的android.util.Log类的标准日志条目,如果可能只有某些(自定义) TAGS

任何人有一个例子或任何好的提示如何达到这个?

提前致谢

Solutions Collecting From Web of "扩展Android.util.Log以写入文件"

您可以以编程方式读取日志猫,并将其存储到文本文件中,或者将其发送到任何您想要的地方。

下面是我写的相同的详细文章

在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(); } } } 

所以有更短的变体

尝试{
    最终文件path=新文件(
             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();
 }