Android 以编程方式捕获 LogCat 还是将其导出到文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23807689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:29:37  来源:igfitidea点击:

Catch LogCat programmatically or export it to file?

android

提问by Amit_android

I want to filter a logcat

我想过滤一个 logcat

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

Working fine for me but not for mytag .

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

I am also using the code:

我也在使用代码:

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";  

But it returns empty file.

但它返回空文件。

回答by Robert P

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

also use

也用

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.

回答by Amit_android

File filename = new File(Environment.getExternalStorageDirectory()+"/mylog.log"); 
filename.createNewFile(); 
String cmd = "logcat -d -f"+filename.getAbsolutePath();
Runtime.getRuntime().exec(cmd);

it works for me. but for all logcat output not for special tag(mytag).

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

回答by Robert P

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

also you need

你也需要

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

referenced here

参考这里

回答by bendaf

I have created a class for saveing logcat to file, check this:

我创建了一个用于将 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");
    }
}

Call the FileLogHelper.getInstance().addLogTag(<YOUR_TAG>);function in your onCreate() for example and the folder will be placed the default external storage, which is /storage/emulated/0/on the most of the phones.

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

Please let me know if you find any bug in the code!

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

回答by Ijas Ahamed N

Some phone can't write to external directory. So we have to write to android cache directory

有些手机无法写入外部目录。所以我们必须写入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);
}

Above method will write all logs into the file. Also please add below permissions in Manifest file

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

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

回答by Ramesh Bandari

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