Omar
Omar

Reputation: 3040

Angular 6: Made a log service... I need help getting the original file path

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

_global.ts

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);
    }
};

example.component.ts

_log(' == products ==> ', 'i', products);

screenshot

enter image description here

question

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

Answers (1)

Ashish Ranjan
Ashish Ranjan

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

Related Questions