Android Programming : Implementing Logging with Preferences


Hello techies, I am sharing you the class I wrote for recording logs in the android application.

Sometimes you need these logs to troubleshoot the application behavior. For this you have to have mechanism to write logs from every method/class in a file which you can refer later but the problem is you can not keep it recording for ever. It will eat-up the user’s memory and will also eat up the CPU. To minimize the loss, we can give preference to the users in the form of settings and they can turn logs on or off.

 

Below is the class called MyLogger which implements the methods to record the logs to user’s SDCard.

 

package com.aslsoft.pocapp;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.os.Environment;


public class MyLogger {

 /**
  *
  * This function is for writing the logs to sdcard.
  * This function will create file with the format "Log_[AppName]_DateToday.txt"
  * at the location /sdcard/[ApplicationName].
  * @param Class_functionName  Name of the Class and function from where to log the comments. Example : "MainActivity_OnCreate"
  * @param LogContent  The content that needs to be logged.
  * @author Mohd Aslam
  * @return It will not return any value.
  *
  */
 public void RecordLog(String Class_functionName, String LogContent )
 {
  FileWriter fw = null;
  File fLogFile;
  File rootsdcard = Environment.getExternalStorageDirectory();
  File dir = new File(rootsdcard.getAbsolutePath(),"/LogMyLocLogs");
  if (!dir.exists())
  {
   dir.mkdirs();
  }
  fLogFile = new File(dir, "MyLog.txt");

  try {
   fw = new FileWriter(fLogFile,true);

  } catch (IOException e) {
    // TODO Auto-generated catch block
   e.printStackTrace();
   try {
    fw.flush();
    fw.close();
   } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }
  }
  try
  {
   fw.append("\n-----------------------------\n");
   fw.append("Class_Function Name:-++->" + Class_functionName);
   fw.append("\nLog:-->" + LogContent + "\n");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally
  {
  }
  try {
   fw.flush();
   fw.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}


 

Add below to your manifest file. This permission will be required to write the log file to the sdcard.

 

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

 

Below is code that needs to be added to use the class and its method from the class to record the logs.

 

//declare global variable of the class MyLogger
 public MyLogger mylog=new MyLogger();

//Calling RecordLog method when the Logging option is enabled

if (GetPrefSettings("LoggingOn"))
{
    mylog.RecordLog("MainActivity_OnCreate", “My log”);
}

 

Below is the class where the setting (Log on/off) is implemented and the user preference is recorded. It has two functions to add and get preference. SharedPreferences class is used to set and get the preferences.

 

/**
 *
 */
package com.aslsoft.pocapp;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.Window;

/**
 * @author Mohd Aslam
 * Class for Application settings and preferences
 */
public class ApplicationSettings extends PreferenceActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.my_app_settings);
  CheckBoxPreference cbfSetting = (CheckBoxPreference) getPreferenceManager().findPreference(getResources().getString(R.string.Pref_IsLogEnabled));
  cbfSetting.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

   @Override
   public boolean onPreferenceChange(Preference preference, Object newValue) {
    // TODO Auto-generated method stub
    AddPrefSettings((Boolean) newValue);
    return true;
   }
  });

  cbfSetting.setChecked(GetPrefSettings(getResources().getString(R.string.Pref_IsLogEnabled)));
 }

//Method to add preferences
 public void AddPrefSettings(boolean IS_LOGGING_ON)
 {
  SharedPreferences MyPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  SharedPreferences.Editor MyPrefeditor = MyPreferences.edit();
  MyPrefeditor.putBoolean(getResources().getString(R.string.Pref_IsLogEnabled), IS_LOGGING_ON);
  MyPrefeditor.commit();
 }
 // Method to get Preferences
 public boolean GetPrefSettings(String strPrefKey)
 {
  SharedPreferences MyPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  return MyPreferences.getBoolean(strPrefKey, false);
 }

}

 

Below is the XML file for the settings screen:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    <PreferenceCategory android:title="My Application Settings">
        <CheckBoxPreference
            android:summary="This will enable/disable the logs"
            android:title="Enable Logs"
            android:persistent="true"
            android:defaultValue="false"
            android:key="@string/Pref_IsLogEnabled"/>"
    </PreferenceCategory>
</PreferenceScreen>

 

 

 

Results:

My Applications Settings screen:

 

clip_image002

 

MyLog file in its destination directory:

 

clip_image002[5]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s