【问题标题】:Catch LogCat programmatically or export it to file?以编程方式捕获 LogCat 或将其导出到文件?
【发布时间】:2014-05-22 13:05:25
【问题描述】:

我想过滤一个 logcat

String myCommand="logcat -f /sdcard/output.txt"; //no filters, keep writing  
myCommand="logcat -d -f /sdcard/output.txt"; //no filters, just a dump

对我来说很好,但对 mytag 来说不行。

我也在用代码:

String myCommand="logcat myTag *:S"; //the equivalent of logcat -s myTag  
myCommand="logcat -s myTag:D";   
myCommand="logcat -s myTag:E myTag2:D";  
myCommand="logcat myTag:E myTag2:D";  

但它返回空文件。

【问题讨论】:

    标签: android


    【解决方案1】:
    try {
       File filename = new File(Environment.getExternalStorageDirectory()+"/gphoto4.html"); 
            filename.createNewFile(); 
            String cmd = "logcat -d -f "+filename.getAbsolutePath();
            Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    

    也用

    String cmd = "logcat -v time -r 100 -f <filename> [TAG]:I [MyApp]:D *:S";
    Runtime.getRuntime().exec(cmd);
    
    
    -v -> Sets the output format for log messages.
    -r -> for specifying the size of file.
    -f -> file to which you want to write the logs.
    [TAG] -> Tag of your application's log.
    [MyApp] -> Your application name.
    

    【讨论】:

    【解决方案2】:
    File filename = new File(Environment.getExternalStorageDirectory()+"/mylog.log"); 
    filename.createNewFile(); 
    String cmd = "logcat -d -f"+filename.getAbsolutePath();
    Runtime.getRuntime().exec(cmd);
    

    它对我有用。但对于所有 logcat 输出,不是特殊标签(mytag)。

    【讨论】:

    【解决方案3】:
    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) {
    }
    }
    }
    

    你也需要

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

    引用here

    【讨论】:

      【解决方案4】:

      我创建了一个用于将 logcat 保存到文件的类,请检查:

      import android.os.Environment;
      import android.util.Log;
      
      import java.io.File;
      import java.io.IOException;
      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.Locale;
      
      /**
       * This singleton class is for debug purposes only. Use it to log your selected classes into file. <br> Needed permissions:
       * READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, READ_LOGS" <br><br>Example usage:<br> <code> FileLogHelper.getInstance().addLogTag(TAG);</code>
       * <p/>
       * Created by bendaf on 2016-04-28 
       */
      public class FileLogHelper{
          private static final String cmdBegin = "logcat -f ";
          private static final boolean shouldLog = true; //TODO: set to false in final version of the app
          private static final String TAG = "FileLogHelper";
      
          private String logFileAbsolutePath;
          private String cmdEnd = " *:F";
          private boolean isLogStarted = false;
          private static FileLogHelper mInstance;
      
          private FileLogHelper(){}
      
          public static FileLogHelper getInstance(){
              if(mInstance == null){
                  mInstance = new FileLogHelper();
              }
              return mInstance;
          }
      
          public void initLog(){
              if(!isLogStarted && shouldLog){
                  SimpleDateFormat dF = new SimpleDateFormat("yy-MM-dd_HH_mm''ss", Locale.getDefault());
                  String fileName = "logcat_" + dF.format(new Date()) + ".txt";
                  File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/logcat/");
                  if(outputFile.mkdirs() || outputFile.isDirectory()){
                      logFileAbsolutePath = outputFile.getAbsolutePath() + "/" + fileName;
                      startLog();
                  }
              }
          }
      
          private void startLog(){
              if(shouldLog){
                  try{
                      File prevLogFile = new File(logFileAbsolutePath);
                      prevLogFile.delete();
                      Runtime.getRuntime().exec(cmdBegin + logFileAbsolutePath + cmdEnd);
                      isLogStarted = true;
                  }catch(IOException ignored){
                      Log.e(TAG, "initLogCat: failed");
                  }
              }
          }
      
          /**
           * Add a new tag to file log.
           *
           * @param tag      The android {@link Log} tag, which should be logged into the file.
           * @param priority The priority which should be logged into the file. Can be V, D, I, W, E, F
           *
           * @see <a href="http://developer.android.com/tools/debugging/debugging-log.html#filteringOutput">Filtering Log Output</a>
           */
          public void addLogTag(String tag, String priority){
              String newEntry = " " + tag + ":" + priority;
              if(!cmdEnd.contains(newEntry)){
                  cmdEnd = newEntry + cmdEnd;
                  if(isLogStarted){
                      startLog();
                  }else{
                      initLog();
                  }
              }
          }
      
          /**
           * Add a new tag to file log with default priority, which is Verbose.
           *
           * @param tag The android {@link Log} tag, which should be logged into the file.
           */
          public void addLogTag(String tag){
              addLogTag(tag, "V");
          }
      }
      

      例如,在 onCreate() 中调用 FileLogHelper.getInstance().addLogTag(&lt;YOUR_TAG&gt;); 函数,该文件夹将被放置为默认的外部存储,在大多数手机上为 /storage/emulated/0/

      如果您在代码中发现任何错误,请告诉我!

      【讨论】:

      • 请注意 - 您不应该在 android 环境中使用 java 单例。这是一种反模式。
      • 感谢您的来信!您能帮我吗,您将如何创建一个在整个应用生命周期中保持一致的记录器?
      • 依赖注入,如匕首。创建每个活动都可以引用和使用的应用程序单例。这样,它就是一个生命周期附加到应用程序的单个对象。
      • @LEO 我认为使用第三方不必要的低性能大型库,如 Dagger 和其他,总体上没有区别,只是为了个人品味和个人舒适(并且没有冒犯主要是为业余爱好者创建的) , 比一个简单的小单例类更“反模式”。来自google.github.io/daggerDagger is a fully static, compile-time dependency injection framework for both Java and Android. It is an adaptation of an earlier version created by Square and now maintained by Google.
      • 创建文件...但不写日志
      【解决方案5】:

      部分手机无法写入外部目录。所以我们必须写入android缓存目录

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

      上述方法会将所有日志写入文件。另外请在 Manifest 文件中添加以下权限

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

      【讨论】:

        【解决方案6】:
        public static void printLog()
        
        {
        
              String filename = Environment.getExternalStorageDirectory().getPath() + File.separator + "myandroidapp.log";
        
              String command = "logcat -f "+ filename + " -v time *:V";
        
              try{
                 Runtime.getRuntime().exec(command);
              }
              catch(IOException e){
                 e.printStackTrace();
              }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-11-13
          • 1970-01-01
          • 2018-11-08
          • 2013-08-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多