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.
Android:
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)
Log.d(“YOUR_APP_NAME”,
”Class: ”+stackTraceElements[1].getClassName() +
“Method: ”+stackTraceElements[1].getMethodName() +
“Line: ”+stackTraceElements[1].getLineNumber() +
“Message: ”+logMessage);
} // end of log
iOS:
Swift 2.2:
func log(logMessage: String, functionName: String = #function, controllerName: String = #file){
if DEBUG {
let file = controllerName.componentsSeparatedByString(“/”).last!.componentsSeparatedByString(“.”).first!
print(“\(file) :: \(functionName) -> \(logMessage)”)
}
}
Objective-C:
Cordova:
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.
if(DEBUG)
console.log(arguments.callee.caller.name, object);
}