是否可以将日期/时间绑定到控制台日志
Is it possible to bind a date/time to a console log?
我有以下代码:
var myLog = console.log.bind(console, '[DEBUG]');
当我想把用[DEBUG]
准备好的东西记录到控制台时,它就可以找到了。现在我想在日志中添加一个日期/时间,我尝试了这个:
var myLog = console.log.bind(console, '[DEBUG ' + (new Date) + ']');
这显然不起作用,因为总是记录相同的时间(调用.bind
的时间)。
是否有任何方法(使用.bind
)在每个日志上记录当前时间而不必这样做:
var myLog = function(){
var args = ['[DEBUG ' + (new Date) + ']'];
for(var i = 0; i < arguments.length; ++i) {
args.push(arguments[i]);
}
return console.log.apply(console, args);
};
因为上面的方法显示了调用console.log.apply
的行,而不是调用myLog
的行。
是。http://jsfiddle.net/SwFJg/6/
var DEBUG = (function(){
var timestamp = function(){};
timestamp.toString = function(){
return "[DEBUG " + (new Date).toLocaleTimeString() + "]";
};
return {
log: console.log.bind(console, '%s', timestamp)
}
})();
DEBUG.log("banana", {foo:'bar'}); //[DEBUG 2:43:21 PM] banana Object {foo: "bar"}
console.log("Peppercorn"); //Peppercorn
DEBUG.log("apple"); //[DEBUG 2:43:21 PM] apple
DEBUG.log("orange"); //[DEBUG 2:43:21 PM] orange
setTimeout(function(){
DEBUG.log("mango"); //[DEBUG 2:43:25 PM] mango
},3000)
这是因为每次调用console.log
时,都会在timestamp
上调用toString
(实际上,所有内容)。
我们覆盖默认的toString
方法,并将其替换为时间戳(显然,您可以将输出更改为您想要的任何内容)。
我选择上面的模式是因为,正如其他人(在SO聊天中)所指出的,您可以轻松地扩展DEBUG对象来做其他事情。
...
return {
log: console.log.bind(console, '%s', timestamp),
error: console.error.bind(console, '%s', timestamp),
info: console.info.bind(console, '%s', timestamp),
warn: console.warn.bind(console, '%s', timestamp),
group: ...,
groupEnd: ...,
groupCollapsed: ... // etc
}
...
我想这就是你想要的,简单的
console.logCopy = console.debug.bind(console);
console.debug = function(data)
{
var currentDate = '[' + new Date().toUTCString() + '] ';
this.logCopy(currentDate, data);
};
相关文章:
- 在VanillaJS中模拟模型双向数据绑定
- 无法通过数组映射绑定
- 主干-不管怎样,检查事件以前是否绑定过
- 用于搜索的聚合物嵌套绑定
- Angular:更新一次性绑定的数据
- 如何使用ngrepeat和双向绑定获得指令的隔离范围
- react.js中的密钥绑定
- 使用regex的jquery keydown绑定不会验证撇号和句点
- 将事件处理程序绑定到任何可能的事件
- AngularJS指令只识别双向绑定类型
- Telerik rad组合框多列数据绑定
- 对API数据使用声明性绑定
- 如何销毁/删除/取消绑定SnapSVG.js
- 在D3.js中,有没有任何方法可以将x和y方向上的滚动事件绑定到平移svg
- 数据绑定:'系统Char'不包含名为'xxxxx'
- react组件中的绑定方法
- 如何将ngrepeat下的ngmodel绑定到$scope
- WinJS内联绑定语法
- 如何通过控制台调试AngularJS中通过controllerAs绑定到控制器的变量
- 是否可以将日期/时间绑定到控制台日志