【问题标题】:Dump all console javascript outputs as string将所有控制台 javascript 输出转储为字符串
【发布时间】:2019-05-02 13:51:33
【问题描述】:

我有一个问题,我需要获取所有 console.log 输出是否可以将所有 console.log 输出转储到一个变量?我使用 node.js。一点上下文:我有一个 mocha 记者的输出,我希望将所有输​​出格式化并通过电子邮件发送

【问题讨论】:

  • 可能有,但很奇怪,你能提供更多的上下文吗?
  • 最好将它们写入日志文件?
  • 我添加了一个上下文
  • 我不想创建日志文件

标签: javascript node.js


【解决方案1】:

基于@godot 的回答:

var logs = '' // logs needs to be defined for the += operator
const tmp = console.log
console.log = function(...args) {
  // string substitution, console.log style
  const formatArg = util.format(...args)
  logs += formatArg + '\n'
  tmp(...args)
}

// To test it :

console.log('test1')
// use console.log with the "printf" style
console.log('test%d', 2)
// same
console.log('%s%d', 'test', 3)
// now show all the logs that were collected in the global var logs variable
console.log('logs: ', logs) // if you don't like globals, u can also use put it in an attribute of the console object...

【讨论】:

  • 当然,我只添加了util.format 函数,它实现了console.log 正在使用的“字符串替换”。看here的解释,但如果你知道C,它与著名的printf函数非常相似。
  • 函数定义参数中的rest运算符(...)和函数参数中的spread运算符(...call) 允许您将函数的所有参数分别收集在一起并将其传播到一个变量(准确地说是一个数组)中/从一个变量中传播。这里因为我们不知道我们要重现的console.log函数的参数个数,所以超级方便!
  • 我的意思是:编辑答案并解释你的代码,只有代码的答案被标记为低质量的答案。
【解决方案2】:

您可以使用一种技巧,将console.log 替换为decorator pattern 之后的另一个函数:

var logs = ''; // logs needs to be defined for the += operator
const tmp = console.log;
console.log = function(...args){ 
    logs += arg + ' '
    tmp(...args)
}

显然,使用全局变量不是很好,但您可以从那里改进...

【讨论】:

  • 我会尽力让你知道
  • 这很奇怪,但现在我有这样的输出:%d passing (%ss) %d failing undefined %s) %s: %s%s %s
  • 你的信息有点神秘......你期待什么输出?关于undefined,这是正常的。我不知道您是否注意到,但我已更改代码以消除问题。
  • 通常看起来像这样2 passing (24.20s) 1 failing %d 和 %s 它认为需要用数据替换它,但只有在重新定义 console.log 时才会中断
  • 好的,这是因为您的记录器正在使用字符串替换...看看我的更正是否让您更接近您想要的位置(您必须自己实现字符串子才能完成工作) .
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
  • 1970-01-01
  • 1970-01-01
  • 2013-05-13
相关资源
最近更新 更多