我想覆盖Lambda函数中的默认控制台语句,但是它不起作用

const logClone = console.log;

console.success = function () {
  const args = Array.from(arguments);
  args.unshift('SUCCESS -');
  return logClone.apply(console, args);
};
const errorClone = console.error;
console.error = function () {
  const args = Array.from(arguments);
  args.unshift('ERROR -');
  return errorClone.apply(console, args);
};



exports.handler = (event, context, callback) => {
    console.success("I'm in success");
    console.error("I'm in Error");
    callback(null, {statusCode:200,body:'reached'});  // Echo back the first key value
};


输出如下:

SUCCESS - I'm in success
I'm in Error


仅打印SUCCESS,但ERROR不起作用

屏幕截图

javascript - AWS Lambda:console.error不被覆盖-LMLPHP

最佳答案

const logClone = console.log;
console.success = function () {
  const args = Array.from(arguments);
  args.unshift('SUCCESS -');
  return logClone.apply(console, args);
};

const errorClone = console.error;
console.failure = function () {
  const args = Array.from(arguments);
  args.unshift('ERROR -');
  return errorClone.apply(console, args);
};

exports.handler = (event, context, callback) => {
    console.success("I'm in success");
    console.failure("I'm in Error");

    console.error('testing')
    callback(null, {statusCode:200,body:'reached'});  // Echo back the first key value
};


使用上面的代码,您可以在行中添加'ERROR -''SUCCESS-'。但是在node.js中,console.logconsole.error在日志文件中在视觉上都是相同的。只是将console.log输出发送到stdout,将console.error输出发送到stderr。在浏览器中,您可以看到它们之间的视觉差异。我相信,Lambda会将stdout和stderr都重定向到可以在cloudwatch中看到的文件。

但是,在Python中,logger.error(similar to console.error)在该行开头的时间戳记之前添加一个额外的[ERROR]文本,这使识别错误更加容易。

关于javascript - AWS Lambda:console.error不被覆盖,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46605096/

10-12 00:19
查看更多