简体   繁体   English

ES6-用替换包装console.log()

[英]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. 看来我当前的实现破坏了console.log()的令牌替换机制。 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); 尝试替换您的字符串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. 您不能在替换标记的string中使用替换。 The best you could do is to use string concatenation to construct the first argument you pass to console.log . 最好的办法是使用string串联来构造传递给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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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