简体   繁体   中英

ES6 - Wrapping console.log() with substitutions

I have a custom logger that adds extra formatting when outputting to console.

class Logger {

    Log(moduleId, message, ...args) {
        var d = new Date(),
            h = (d.getHours()<10?'0':'') + d.getHours(),
            m = (d.getMinutes()<10?'0':'') + d.getMinutes(),
            s = (d.getSeconds()<10?'0':'') + d.getSeconds();
        var timestamp = h + ":" + m + ":" + s;

        console.log('[%s | %s] - %s', timestamp, moduleId, message, ...args);
    }

}

var instance = new Logger();
module.exports = instance;

It would then be called like so:

Logger.Log('Web', 'Request %s completed in %dms MS', url, new Date() - benchmark);

The expected result would be

[20:03:30 | Web] - Request http://example.com completed in 193dms MS

However, instead what outputs is

[20:03:30 | Web] - Request %s completed in %dms MS http://example.com 193

It seems that my current implementation breaks console.log() 's token substitution mechanism. Why is this happening and how can I get around it?

Try to replace your string console.log('[%s | %s] - %s', timestamp, moduleId, message, ...args); with

console.log(`[${timestamp} | ${moduleId}] - ${message}`, ...args);

You cannot use substitution in the string that is substituting a token. The best you could do is to use string concatenation to construct the first argument you pass to console.log .

Here is an example.

 class Logger { static Log(moduleId, message, ...args) { var d = new Date(), h = (d.getHours()<10?'0':'') + d.getHours(), m = (d.getMinutes()<10?'0':'') + d.getMinutes(), s = (d.getSeconds()<10?'0':'') + d.getSeconds(); var timestamp = h + ":" + m + ":" + s; console.log('[%s | %s] - ' + message, timestamp, moduleId, ...args); } } Logger.Log('Web', 'Request %s completed in %dms MS', "https://....", 10); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM