如何在没有换行符的情况下以正确的缩进打印error.stack

时间:2019-05-07 07:34:33

标签: javascript node.js winston

这是我的日志,由console.log打印。

2019-05-07T07:28:44.246Z[error]: {
  "message": "Unexpected end of JSON input",
  "service": "better-logging",
  "timestamp": "2019-05-07T07:28:44.246Z",
  "stack": "SyntaxError: Unexpected end of JSON input\n    at JSON.parse (<anonymous>)\n    at Object.findById (/Users/ldu020/workspace/github.com/mrdulin/nodejs-gcp/src/stackdriver/better-logging/logger.spec.js:18:12)\n    at Object.findById (/Users/ldu020/workspace/github.com/mrdulin/nodejs-gcp/src/stackdriver/better-logging/logger.spec.js:8:15)\n    at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/nodejs-gcp/src/stackdriver/better-logging/logger.spec.js:27:15)\n    at Module._compile (module.js:652:30)\n    at Object.Module._extensions..js (module.js:663:10)\n    at Module.load (module.js:565:32)\n    at tryModuleLoad (module.js:505:12)\n    at Function.Module._load (module.js:497:3)\n    at Function.Module.runMain (module.js:693:10)"
}

如您所见,stack字段的值包含许多换行符\n

我要使用正确的缩进来打印stack

"SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at Object.findById (/Users/ldu020/workspace/github.com/mrdulin/nodejs-gcp/src/stackdriver/better-logging/logger.spec.js:18:12)
    at Object.findById (/Users/ldu020/workspace/github.com/mrdulin/nodejs-gcp/src/stackdriver/better-logging/logger.spec.js:8:15)
    at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/nodejs-gcp/src/stackdriver/better-logging/logger.spec.js:27:15)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)"

我很奇怪将字符串复制到chrome浏览器的console中,然后格式正确。

注意::输出已通过console.log方法打印。而且,我无法再次致电console.log。我可以获得stack的值,所以我需要一些格式化代码来处理字符串。

更新

我使用winston记录器模块。这是我的配置:

const printf = format.printf((info) => {
    const { level, ...rest } = info;
    let log;
    if (rest.stack) {
      //rest.stack = rest.stack.split('\n').map((line) => {
       // return line.trim();
      //});
      log = rest;
    }
    log = JSON.stringify(rest, null, 2);
    return `${info.timestamp}[${info.level}]: ${log}`;
  });
  transports = [
    new winston.transports.Console({
      format: format.combine(format.colorize(), format.timestamp(), format.errors({ stack: true }), printf)
    })
  ];

3 个答案:

答案 0 :(得分:0)

这是因为您要对err对象进行字符串化,因此可以使用String.prototype.replace

将所有'\ n'替换为已解析的行更改
    const printf = format.printf((info) => {
    const { level, ...rest } = info;
    let log;
    if (rest.stack) {
      //rest.stack = rest.stack.split('\n').map((line) => {
       // return line.trim();
      //});
      log = rest;
    }
    log = JSON.stringify(rest, null, 2).replace(/\\n/g, '\n');
    return `${info.timestamp}[${info.level}]: ${log}`;
  });
  transports = [
    new winston.transports.Console({
      format: format.combine(format.colorize(), format.timestamp(), format.errors({ stack: true }), printf)
    })
  ];

例如,请参见以下摘录

try {
	JSON.parse('\"');
} catch(err) {
	err.stacks = err.stack;
	console.log(JSON.stringify(err))
}

try {
	JSON.parse('\"');
} catch(err) {
	err.stacks = err.stack;
	console.log(JSON.stringify(err).replace(/\\n/g, '\n'))
}

答案 1 :(得分:0)

这是我的解决方法,因为我叫JSON.stringify(error),所以有很多换行符号\n。现在,我只需要console.log(stack)

const printf = format.printf((info) => {
    const { level, ...rest } = info;
    let log;
    if (rest.stack) {
      const { stack, ...others } = rest;
      log =
        `${info.timestamp}[${info.level}]: ${JSON.stringify(others, null, 2)}\n` +
        `${info.timestamp}[${info.level}]: ${stack}`;
    } else {
      log = `${info.timestamp}[${info.level}]: ${JSON.stringify(rest, null, 2)}`;
    }
    return log;
  });
  transports = [
    new winston.transports.Console({
      format: format.combine(format.colorize(), format.timestamp(), format.errors({ stack: true }), printf)
    })
  ];

然后,输出错误日志。

enter image description here

答案 2 :(得分:0)

请参阅本文,特别是他们提到console.group()的部分。
我相信这就是您要寻找的。

https://blog.teamtreehouse.com/mastering-developer-tools-console#attachment_22938