How to store Android Log entry as a string

196 Views Asked by At

I can't seem to find an answer or a question regarding this:

How do I store an Android Log entry to a string:

Log.i(TAG, "onCreate: start: ");

String s = /* get last Log entry */.toString();

The reason for this is so I can have the process ID and thread IDs. When I try to manual store the process and thread IDs, the thread IDs are different than printed in Logcat:

Log.i(TAG, "#checkWifiConnection: start");
String s = Integer.toString(android.os.Process.myPid()) + " " + Integer.toString(android.os.Process.getThreadPriority(android.os.Process.myTid())) + " " + TAG;
System.out.println(s + "#checkWifiConnection: start");

Logcat shows:

01-09 18:38:02.994 1558-2021 I/*~FETCH DATA: #checkWifiConnection: start

System.out shows:

I/System.out: 1558 10 *~FETCH DATA#checkWifiConnection: start
2

There are 2 best solutions below

5
Skizo-ozᴉʞS ツ On BEST ANSWER

How do I store an Android Log entry to a string

You can not do this.

From Log documentation

Generally, you should use the Log.v(), Log.d(), Log.i(), Log.w(), and Log.e() methods to write logs. You can then view the logs in logcat.

They are only for Logcat in debug section, so I recommend you to look for another way to store your desire.

For instance you could create a class, that stores all of the Log you have, and then store it wherever you want.

I already know how to store some information into a seperate class but the reason I wanted Log.toString was for the time stamps, process IDs, and thread IDs

Then create more attributes for this specific class and pass them whenever you want.

To store the Process id use

int pid = android.os.Process.myPid();

To store the Thread id use

int tid = android.os.Process.getThreadPriority(android.os.Process.myTid());

To store the timestamp use

SimpleDateFormat s = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String format = s.format(new Date());
0
Adam On

I dont think its possible to do that however you could make your own object which handles log calls and sets a string instance variable to the last message. You can then retrieve this string from the object