Reputation: 3040
In my angular project i have a _global function for logging stuff in the browser so i can turn on and off debug mode easy. My problem is the console reads the location of the logs are all from the _global file but im looking for an easy way to detect the original location of the _log
export const _log = function(msg, style, data?) {
if(this.mode.dev_mode){
data = (data) ? data : '';
let s = "";
switch ( style ) {
case 't':
s = "background: #222; color: #bada55";
break;
case 'i':
s = "background: #efefef; color: blue; 'font-weight:900;'";
break;
case 'e':
s = "background: red; color: white; 'font-weight:bold;'";
break;
case 'd':
s = "background: #333; color: white; 'font-weight:bold;'";
break;
case 'y':
s = "background: #FFBB3B; color: white; 'font-weight:bold;'";
break;
case 's':
s = "background: green; color: white; 'font-weight:bold;'";
break;
default:
s = "background: #222; color: #bada55";
}
console.log(`%c ${msg}`, s, data);
}
};
_log(' == products ==> ', 'i', products);
see how all logs say _global.ts what is an easy way to not somehow the original function usage? in this case for example would be example.component.ts
instead of _global.ts
... I could just type it out everytime but id rather something more automated and allows me to keep the _log() short.
Upvotes: 1
Views: 2239
Reputation: 12960
This is ugly and doesn't exactly serve what you have asked but this is what I could make, see if it works for you.
In example.component.ts or any component
_log(' == products ==> ', 'i', (new Error()), products);
In _global.ts
export const _log = function(msg, style, error, data) {
let infoLine = error.stack.split('\n')[1];
// very ugly but I found it consistent
let startingIndex = infoLine.indexOf('(') + 1;
let endingIndex = infoLine.indexOf(')');
let fileNameAndLine = (infoLine.substring(startingIndex, endingIndex))
...
console.log(`%c ${msg} at ${fileNameAndLine}`, s, data);
}
See this for more: How can I determine the current line number in JavaScript?
Upvotes: 1