Now and then you must feel the need to have some more control over the way Android Application logs are getting displayed. Possible requirement scenarios; redirecting your Android logs into a File or you might want to control the logs those are getting displayed e.g. for production mode, you may want to block all logs to get better performance.
I have written a custom Logger, which is a wrapper over android.util.Log. This will keep existing behavior of Log class as it is and add few handy features to get more control over your application logs-
Storing Logs directly into File
- at present all logs comes on the LogCat. You need to manually copy/past logs from LogCat to any file for further analysis. Another option is to get the Dump state when an application gets “Forced Closed”. But this wrapper will allow you an automatic solution. Imagine a scenario, your Phone is not connected with the LogCat and you need the tracing. This wrapper will be helpful in this scenario.
Controlled Logging
- it will give you the control to select the range of logs to be display/stored e.g. if you select the allowed Log Level to VERBOSE, all Log Level (integer values) higher than VERBOSE will be displayed. You can even completely block all logging (perfect for production).
To get above additional benefits, you need to refer to a new Class instead of android.util.Log-
MLog.i(“TAG”, “
Log Message
”)
All methods are static and make sure, you call
MLog.init(context, “
Log_File_Name
”)
at the very beginning (probably in the
onCreate()
method of your Activity). This utility class will create a log file under
data/data/
Your_Application_Package
/files/
Log_File_Name
Sample usage scenarios-
Step1- Configure the Logger (Optional Step)
To stop logging-
MLog.enableLog = false; (this will be suitable for Production Release)
To enable logging only of INFO, WARN and ERROR-
MLog.logLevel = MLog.INFO;
Step2- Initialize the Logger
Once you set above properties, initiate the logger-
MLog.init(this.getApplicationContext(), "app_log.txt");
Note: be careful to pass Application Context rather than Activity Context, which might cause Leak Window issue.
Step3- Use the Logger. Same as you use Log.i(TAG, msg), Log.v(TAG, msg)
MLog.i(TAG, "Location Activity...");
So now you can get these additional benefits by using the attached Logger (MLog.java) in your next project. Have a happy and controlled logging :-)