I have gathered various solutions from this page along with others to create a simple demo in JSFiddle. The demo showcases the use of the $log service and how it can be enhanced with decorators to include line numbers (indicating where the $log call was made). Additionally, I have developed a more detailed solution in Plunker, demonstrating the $log service with added features like displaying line numbers, caller file name, and instance name. I hope this will be beneficial to others.
JSFiddle URL - https://jsfiddle.net/abhatia/6qnz0frh/
This JSFiddle demo has been tested on the following browsers:
- IE 11 - (JSFiddle Javascript's first line number is 72).
- Firefox 46.0.1 - (JSFiddle Javascript's first line number is 72).
- Chrome 50.0.2661.94 m - (JSFiddle Javscript's first line number is 71).
The results are satisfactory. However, please note that the line number may vary by 1 in Chrome compared to FF or IE due to differences in JSFiddle's JavaScript code structure as listed above.
Plunker URL - https://embed.plnkr.co/YcfJ7V/
This Plunker demo illustrates the concept effectively with detailed explanations. It also displays console outputs using Angular's official example of default $log service for comparison. The Plunk has also been cross-tested on the aforementioned browsers.
The screenshot below shows the console output from the Plunker example highlighting 3 key areas:
- A red box indicating console output using the default $log service, with $log functions invoked from the controller.
- A blue box showcasing console output using the extended $log service, revealing script names, line numbers, and controller names used during $log instantiation.
- An orange box contrasting console outputs of default and extended $log services.
https://i.sstatic.net/Ty7gS.jpg
This distinction becomes clearer when reviewing the Plunk's code.
Below is the getLineNumber function utilized in JSFiddle (a slightly improved version is employed in the Plunker example to fetch caller file names):
function getLineNumber(newErr, sliceIndex1, sliceIndex2)
{
var lineNumber = -1;
var lineLocation;
var stack = newErr.stack.split('\n').slice(2);
if (navigator.userAgent.indexOf("Chrome") > -1) {
stack.shift();
}
stack = stack.slice(sliceIndex1, sliceIndex2);
var stackInString = stack + '';
var splitStack;
if (navigator.userAgent.indexOf("Chrome") > -1) {
splitStack = stackInString.split(" ");
}
else {
splitStack = stackInString.split("@");
}
lineLocation = splitStack[splitStack.length - 1];
//console.log(lineLocation);
lineNumber = lineLocation.split(":")[2];
return lineNumber;
}