Wrapping console.debug()

Override method with Object.defineProperty.

by tekki_mariani

TypeScript

class Logger {

		// Don't forget console needs to be set to 'All levels' to display debug. ;)

		public OFF = 0;
		public LOG = 1;
    // ...
    public ALL = 9;
    
		private level = 1;
    
    public constructor() {
        /*this.init();*/ // killed for testing
    }
    
    // This is the original method.
    // Color is fine, but wrong line and file.
    public todo(message?: string, ...optionalParams: any[]) {
        const css = 'background: #FF0000; color: #0000FF';
        optionalParams.length != 0
        		? console.debug('%c[TODO] '+message, css, optionalParams) 
            : console.debug('%c[TODO] '+message, css);
    }    
     
    // This overrides the todo method and gives the correct line and file,
    // but the color is destroyed.
    // And the optionalParams no longer an array.
    /*private*/ public init() { // public for testing.
        Object.defineProperty(this, "todo", {get: function () {
            return this.level >= this.LOG 
                ? console.debug.bind(console, '%c[TODO]', 'background: #FF0000; color: #0000FF') 
                : function(){};},
            configurable: true
        });    	
    }
    
    public setLevel(level: Level) {
        this.level = level;
        this.init();
    }

}


// Test
const logger = new Logger();

logger.todo('normal todo().');
logger.todo('normal todo() with data.', 666, 777);

logger.init(); // This is why init is not called in constructor and public. ;)

logger.todo('modified todo().');
logger.todo('modified todo() with data.', 666, 777);