Logging Util in the mobile application to help you debug the application faster

When an airplane is flying, black box (flight data recorder) is recording everything. If something goes wrong, log helps to figure out what happened. When a program crashes, if there is no proper logging done, we have little chance to understand what happened. Without the log, finding what went wrong is difficult.

Traversing the flow of app when we have only print statements is time taking and a tedious task, if the bug is found in integration testing while testing 3-4 workflows all together.

Although logging is important, not all developers know how to use them correctly. Some developers insert print statements, Log.d method or console.log when developing and remove those statements when it is finished.

Why not create our own function to print logs which will take care of things in an efficient way.

Finding which function printed the log is difficult using the print statements.
One option is to write the function name in the print statement, Log.d method or console.log method but that makes it tiresome as the developer has to write the function name again and again.
A better option is to create a function which will take care of it. Not only it will print the function name but also class name.

Here are some of the logger functions which can be used.

This function will log the class name, method name along with the line number. Note this will print only if the app is in debug mode.

public static void log(String logMessage) {
        Exception exception = new Exception();
        StackTraceElement[] stackTraceElements = exception.getStackTrace();

        //check App is in debug mode.
        if (BuildConfig.DEBUG)
                ”Class: ”+stackTraceElements[1].getClassName() +
                “Method: ”+stackTraceElements[1].getMethodName() +
                “Line: ”+stackTraceElements[1].getLineNumber() +
                “Message: ”+logMessage);
} // end of log


        Swift 2.2:

let DEBUG = true //change to false to stop logging.
func log(logMessage: String, functionName: String = #function, controllerName: String = #file){
        if DEBUG {
                let file =                 controllerName.componentsSeparatedByString(“/”).last!.componentsSeparatedByString(“.”).first!
                print(“\(file) :: \(functionName) -> \(logMessage)”)


#define log(fmt, …) NSLog((@”%s [Line %d] ” fmt), __PRETTY_FUNCTION__, __LINE__,##__VA_ARGS__)

Function prints the name of the caller function and message or object to be printed. if it is not a anonymous function, else it prints blank for the anonymous function.

function log(object){
                console.log(arguments.callee.caller.name, object);
Categories: Mobility

Leave a Reply

Your email address will not be published. Required fields are marked *