8

I want to filter a 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 .

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.

Harikrishnan
  • 7,765
  • 13
  • 62
  • 113
Amit_android
  • 498
  • 2
  • 5
  • 20

6 Answers6

16
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.
Robert P
  • 137
  • 2
  • 10
  • 4
    See [logcat command-line tool](https://developer.android.com/studio/command-line/logcat.html) for further logcat executable arguments – Eido95 Apr 28 '17 at 12:02
11
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).

Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
Amit_android
  • 498
  • 2
  • 5
  • 20
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) {
}
}
}

also you need

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

referenced here

Robert P
  • 137
  • 2
  • 10
2

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

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.

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

bendaf
  • 2,981
  • 5
  • 27
  • 62
  • Just a note - you shouldn't use a java singleton in an android environment. It's an anti-pattern. – LEO Jan 03 '17 at 14:04
  • Thanks for the note! Can you help me than, how would you create a logger which stays consistent accross de app lifecycle? – bendaf Jan 07 '17 at 22:25
  • 2
    Dependency Injection, like dagger. Create an application singleton that each activity can reference and use. That way it's a single object who's lifecycle is attached to the application. – LEO Jan 09 '17 at 01:43
  • 2
    @LEO I think using third-party unnecessary low performance huge libraries like Dagger and others, which make no difference overall and are just for one's personal taste and personal comfort (and no offense mostly created for amateurs ), is way more "anti-pattern" than a simple little singleton class. from https://google.github.io/dagger/ : `Dagger 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.` – M D P Apr 18 '17 at 12:18
  • creating file...but not writing log – Manoj Behera Jul 23 '18 at 10:54
  • @Manoj Behera Are you sure that you are logging with the specified to logcat? – bendaf Jul 30 '18 at 07:51
  • @bendaf : I found `logcat` folder but can't find `logcat_` file. Can you please update for same. – Mehul Kabaria Dec 21 '18 at 04:53
  • @MehulKabaria the output file is created only when the log started, so most probably you did not log anything with . Search in your logcat for the tag and don't forget to call 'FileLogHelper.getInstance().addLogTag();' also! – bendaf Jan 02 '19 at 16:08
  • @MDP calling dependency injection 'low performance' and 'created for amateurs' shows a huge lack of knowledge. That's utterly misleading - you should go back to the basics and learn solid principles. – Nick Cardoso Jan 13 '21 at 10:53
  • @NickCardoso Yes that comment is for 4 years ago when I was an amateur myself – M D P Jan 17 '21 at 06:31
1

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

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" />
Ijas Ahamed N
  • 5,632
  • 5
  • 31
  • 53
-1
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();
      }
}
Alex
  • 781
  • 10
  • 23
Ramesh Bandari
  • 148
  • 2
  • 6