Samuel Thompson
Samuel Thompson

Reputation: 2574

Overwrite chrome console log location with custom logging

When you use console.log('hi') in chrome it prints out the location of where the log came from. The problem I have is that I am intercepting the console log right now in chrome like this.

this.originalConsoleLog = console.log;

console.log = this.log.bind(this);

function log(message?: any, ...optionalParams: any[]): void {
  this.originalConsoleLog(message, optionalParams);
  this.splunkLogger('LOG', message, optionalParams);
}

So in chrome anything that I log now will come from this location which is REALLY annoying trying to figure out where my problems are coming from now.

Here is an example: enter image description here

I want that to not say logger.service.ts:36, and instead say desktop.ts:24, or funtime.ts:69 it is not at all helpful in its current form. Maybe if I call it with this.originalConsoleLog(arguments); it will ignore my logging function?

Upvotes: 6

Views: 658

Answers (2)

Wouter Schut
Wouter Schut

Reputation: 926

If you don't mind this ugly hack, it works....

        const defaultLogLocation = (l,a)=>l.log(...a);
    
        const customLogger = {
                log: (msg, logFn = defaultLogLocation) => {
                        if (logFn.toString() !== defaultLogLocation.toString()) {
                            throw new Error('What are you trying to do here 🤣?')
                        }                       
                        logFn(console, [`PROCESSED ${msg}`]);
                }
        };
        
        customLogger.log("Wrong location");
        customLogger.log("Shows correct location", (l,a)=>l.log(...a));

You could even use that notation to chose err/warn/etc....

Upvotes: 0

Samuel Thompson
Samuel Thompson

Reputation: 2574

So as @slacks said it is "impossible"

The best way that I found out to do this is to put a condition in my logging service to check if you are local and on local don't overwrite logging. Any overwriting of console log just makes the issue from the question.

Upvotes: -1

Related Questions