Its easy to read logs from logcat and debug the application. But what if you have requirement of collecting that logs and send it as report to server?
What you need to do this is for is a permission to read logs and some source of code.
Step 1:
Write following line in your AndroidManifest.xml file to give permission to read logs.
- <uses-permission android:name="android.permission.READ_LOGS" />
Step 2:
Copy paste following code snippet in your application. This class has readLog method which return you logs read by that method.
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
-
- public class LogsUtil {
-
- public static StringBuilder readLogs() {
- StringBuilder logBuilder = new StringBuilder();
- try {
- Process process = Runtime.getRuntime().exec("logcat -d");
- BufferedReader bufferedReader = new BufferedReader(
- new InputStreamReader(process.getInputStream()));
-
- String line;
- while ((line = bufferedReader.readLine()) != null) {
- logBuilder.append(line + "\n");
- }
- } catch (IOException e) {
- }
- return logBuilder;
- }
- }
Now everything is done. If you want to read logs in application, just use