Writing logs into logcat from your application is very easy. Reading logs is usually used for bug report purposes.
The following code reads logs and write it to file:
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);
}
String logFilePath = Environment.getExternalStorageDirectory() + File.separator + "LogTest.txt";
File logFile = new File(logFilePath);
if (!logFile.exists())
logFile.createNewFile();
FileOutputStream outStream = new FileOutputStream(logFile, true);
byte[] buffer = log.toString().getBytes();
outStream.write(buffer);
outStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
And also you needs two permission for reading logs and write file to external storage:
<uses-permission android:name="android.permission.READ_LOGS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You can add any more parameters to the logcat command string.More info in android developer.
When implementing a bug report feature, with sending logs to yourself, don't forget that many applications outputs personal information into the logcat, so a policy about them is definitely needed.
I hope this post is useful ;-)