How to Create and Read Log on Android Devices

How to create and read Log on Android devices?

View Logs on Android:

To see Debug.Log messages, download Android Studio.
Go to the Android Monitor Tab in the Android Studio then select your device from there.

See the image below:

Sample Image


If you have problems of the logs from the device not showing, restart adb.exe. from the command-line.

Stop it:

adb kill-server

Then start it again:

adb start-server

All I want to see is a clean log that shows errors and my Debug.Log
messages which I usually can see easy and clear on the Unity Console
on Unity on Windows.

1.First filter it with the Unity tag.

Sample Image

2.Disable Development mode from Unity Build Settings. With that on, you will receive extra logs you don't even need.

View Logs on Android without Android Studio:

You can view log from without Android Studio by using the Log Viewer plugin which is free. It will let you see the log on the device itself.

Sample Image


Print Logs from Android Java Plugin:

If you are trying to create log from Java plugin, instead of using the Debug.Log function, use one of the Log functions from Java side.

For example, Log.v, Log.i, and Log.e.

Print Logs from Android C++ Plugin:

If using a C++ plugin, see this plugin from my other question which let's you print log from a C++ plugin with Debug::Log.

Read android device logs from my android application

Your app needs to use the permission android.permission.READ_LOGS. (unsure if this works on unrooted device).

and you need to grant the permission to your app in runtime to access this permission with:

adb shell pm grant <pkg> android.permission.READ_LOGS

(or) programmatically with:

Runtime.getRuntime().exec("pm grant <pkg> android.permission.READ_LOGS");

Then you will be able to get the system logs using shell commands for logcat.
For example, to get a logcat dump as a txt file in the device:

Runtime.getRuntime().exec("logcat -d -f" + " /sdcard/Logcat_file.txt");

will get the logs saved in a txt file in the android device , using which further validation can be done.

How do I get the logfile from an Android device?

Logcollector is a good option but you need to install it first.

When I want to get the logfile to send by mail, I usually do the following:

  • connect the device to the pc.
  • Check that I already setup my os for that particular device.
  • Open a terminal
  • Run adb shell logcat > log.txt

How to read the STORED logs from an attached device in Android Studio

AFAIK, the Android System does not keep a Log File, rather it has a temp buffer which contains logs.

Approach 1:Write logs to file in internal storage through code

You need to write logs to the device by yourself. There are libraries like logback-android which can assist in doing so. You just need to create proper configuration in order to write logs on the device storage.

Approach 2: Write logs to file using adb command

Since you are connected through USB you can do

adb logcat -d > logcat.txt

The above command stores file on PC and not on device. Its in the same directory pointed by the command prompt

Approach 3: Use Android Studio

Connect your device to PC and run Android studio. At the bottom, you have logcat tab. You can view the logs and also save them to a text file.


Creating and Storing Log File on device in Android

Wary or not, External Storage still may be the only way to go. Without root access on the device, you can't really get at anything "Internal" unless you're going to be okay with reading within an application on the device. The docs provide pretty solid guidelines for where to create external files, and if you are using API Level 8 or higher, there are a couple of extra functions that can be used. I'm sure you know this page, but here it is anyway: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

If you're in need of any file io example code... I think I could dig some up...

EDIT - I would start by following the guidelines in the above docs to first confirm the state of the storage. I unfortunately don't have any experience with appending a file in Java, so someone else would definitely be more qualified to answer. This doesn't cover appending, but I have a backup routine in one of my personal apps that looks something like this.

    File backupPath = Environment.getExternalStorageDirectory();

backupPath = new File(backupPath.getPath() + "/Android/data/com.maximusdev.bankrecord/files");

if(!backupPath.exists()){
backupPath.mkdirs();
}

FileOutputStream fos;
try {
fos = new FileOutputStream(backupPath.getPath() + "/recordsbackup.txt");

if(okaytowrite){
for(int i = 0; i < count; ++i){
entry = adapter.getItem(i);
fos.write(entry.toString().getBytes());
fos.write("\n".getBytes());
fos.write(String.valueOf(entry.dateTime).getBytes());
fos.write("\n".getBytes());
fos.write(String.valueOf(entry.sign).getBytes());
fos.write("\n".getBytes());
fos.write(String.valueOf(entry.cleared).getBytes());
fos.write("\n".getBytes());
fos.write(String.valueOf(entry.transDate).getBytes());
fos.write("\n".getBytes());
fos.write(entry.category.getBytes());
fos.write("\n".getBytes());
}
}
fos.close();

Toast.makeText(this, "Backup Complete", Toast.LENGTH_SHORT).show();

} catch (FileNotFoundException e) {

e.printStackTrace();

AlertDialog.Builder delmessagebuilder = new AlertDialog.Builder(this);

delmessagebuilder.setCancelable(false);

delmessagebuilder.setMessage("File Access Error");

delmessagebuilder.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});

delmessagebuilder.create().show();

} catch (IOException e) {

e.printStackTrace();

AlertDialog.Builder delmessagebuilder = new AlertDialog.Builder(this);

delmessagebuilder.setCancelable(false);

delmessagebuilder.setMessage("File Access Error");

delmessagebuilder.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});

delmessagebuilder.create().show();
}

Once I'm ready to write, I'm pulling a custom object (entry) out of an ArrayAdapter (adapter) and converting field valuse to strings and using getBytes() to pass to the FileOutputStream write function. I've done some research and there are quite a few other options for file writing in Java/Android... the FileWriter Class for instance, so it bears further research.

Read all system log android

You cant read all the logs.

read here

public static final String READ_LOGS

Added in API level 1 Allows an application to read the low-level
system log files.

Not for use by third-party applications, because Log entries can
contain the user's private information.

Constant Value: "android.permission.READ_LOGS"

Saving Logcat to a text file in Android Device

Use an Application class at the beginning of your app. That allows a proper file and log handling.

Code below creates a log file at the following location:

/ExternalStorage/MyPersonalAppFolder/logs/logcat_XXX.txt

XXX is the current time in milliseconds. Every time you run your app, a new logcat_XXX.txt file will be created.

public class MyPersonalApp extends Application {

/**
* Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created.
*/
public void onCreate() {
super.onCreate();

if ( isExternalStorageWritable() ) {

File appDirectory = new File( Environment.getExternalStorageDirectory() + "/MyPersonalAppFolder" );
File logDirectory = new File( appDirectory + "/logs" );
File logFile = new File( logDirectory, "logcat_" + System.currentTimeMillis() + ".txt" );

// create app folder
if ( !appDirectory.exists() ) {
appDirectory.mkdir();
}

// create log folder
if ( !logDirectory.exists() ) {
logDirectory.mkdir();
}

// clear the previous logcat and then write the new one to the file
try {
Process process = Runtime.getRuntime().exec("logcat -c");
process = Runtime.getRuntime().exec("logcat -f " + logFile);
} catch ( IOException e ) {
e.printStackTrace();
}

} else if ( isExternalStorageReadable() ) {
// only readable
} else {
// not accessible
}
}

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if ( Environment.MEDIA_MOUNTED.equals( state ) ) {
return true;
}
return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if ( Environment.MEDIA_MOUNTED.equals( state ) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals( state ) ) {
return true;
}
return false;
}
}

you need the correct permissions and name of your application class in your .manifest file:

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

<application
android:name=".MyPersonalApp"
... >

Edit:

if you want to save log of only some particular activities..

replace:

process = Runtime.getRuntime().exec("logcat -f " + logFile);

with:

process = Runtime.getRuntime().exec( "logcat -f " + logFile + " *:S MyActivity:D MyActivity2:D");

Android system log file location

There are a few ways to view the System-Log - but finding the location of the log files is considerabaly harder. I will list 3 options that will allow you to view the logs (either on a device or computer), but I do not know where they are kept. I may be wrong, but from what I have gather, the Android System does not keep a "Log File". Rather, there is a buffer that contains the "Log" (again I may be wrong on this)!




You first option is to install an app from the play-store called
aLogCat. This app is very useful for both viewing and sending logs from your device. It can be setup to Email you the "Log Files" from your device. This method works best with root.

The second method works by using the Android SDK. Connect your device (with USB-Debugging enabled) and, at a Terminal enter the following:

    $ adb logcat -d > logcat.txt

The -d option tells adb to copy the entire File Log from the Android System. Because you seem to know how UNIX Systems work, I won't explain the rest of the command.

A third option (if you are rooted, that is) is to install a Terminal Emulator on your Android device. Open the Terminal Emulator and enter the command:

    $ logcat -d > /sdcard/my-log-file.txt

This will do the same as above (except you don't need a computer, and the file saves on your device/SDcard.
Feel free to change the "/sdcard/my-log-file.txt" part to anything you like, but I strongly recommend you save it to either your external or internal storage - so in short: Save it to a location you can accsess without # (superuser) permission!



Related Topics



Leave a reply



Submit