如何使用正确的缩进打印 error.stack,没有换行符

How to print error.stack with correct indent, without newline symbol

这是我的日志,由 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)
    })
  ];

这是因为您正在将错误对象字符串化,您可以使用 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'))
}

这是我的解决方法,因为我调用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)
    })
  ];

以及错误日志的输出。

看看这篇文章,特别是他们提到的部分 console.group()
我相信这就是你要找的。

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