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

时间:2014-05-22 13:05:25

标签: android

我想过滤一个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";  

但它返回空文件。

6 个答案:

答案 0 :(得分:9)

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.

答案 1 :(得分:8)

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

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

答案 2 :(得分: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

答案 3 :(得分:2)

我创建了一个用于将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(<YOUR_TAG>);功能,该文件夹将被置于默认外部存储设备中,即大多数手机上的/storage/emulated/0/

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

答案 4 :(得分:1)

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

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

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

答案 5 :(得分:0)

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

}