¿Captura LogCat de forma programática o la exporta al archivo?

Quiero filtrar un logcat

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

Trabajo bien para mí, pero no para mytag.

También estoy usando el código:

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

Pero devuelve el archivo vacío.

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

también utiliza

 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. 
 File filename = new File(Environment.getExternalStorageDirectory()+"/mylog.log"); filename.createNewFile(); String cmd = "logcat -d -f"+filename.getAbsolutePath(); Runtime.getRuntime().exec(cmd); 

esto funciona para mi. pero para todos logcat salida no para etiqueta especial (mytag).

He creado una clase para guardar logcat en un archivo, compruebe esto:

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

Llame al FileLogHelper.getInstance().addLogTag(<YOUR_TAG>); función en su onCreate () por ejemplo y la carpeta se colocará el almacenamiento externo predeterminado, que es /storage/emulated/0/ en la mayoría de los teléfonos.

Por favor, hágamelo saber si encuentra algún error en el código!

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

también necesitas

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

referenciado aquí

Algunos teléfonos no pueden escribir en el directorio externo. Así que tenemos que escribir en el directorio de caché de 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); } 

El método anterior escribirá todos los registros en el archivo. También añada los siguientes permisos en el archivo de manifiesto

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

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

}

FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.