NodeJS中缩进的多行日志记录 [英] Indented, multi-line logging in NodeJS

查看:46
本文介绍了NodeJS中缩进的多行日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 JSON.stringify()的对象打印到控制台,以便将上下文作为Mocha测试套件输出的一部分.

I want to print JSON.stringify()'d objects to the console, for context as part of a Mocha test suite output.

随着测试的缩进,我希望对象日志行向右缩进足够的距离(例如3-4个制表符空间),以使它们可以正确识别在正确的 describe()组中.

As the tests indent, I'd like the object log lines to be indented far enough rightwards (say, 3-4 tab spaces) that they are recognisably in the right describe() group.

如何使用 console.log process.stdout.write 之类的东西来实现这一目标?

How could I achieve this with something like console.log or process.stdout.write?

推荐答案

如果仅用于console.log,则可能要查找组,请在控制台上进行检查:

If just used for console.log you might want to look up for groups, check this on your console:

var obj = {
  a : 1,
  b : 2,
  c: 3
  }

console.log('Non-tabbed');
console.group();
console.log(JSON.stringify(obj, null, 2));
console.groupEnd();
console.log('Back to non-tabbed');

在当前浏览器和最新节点上工作正常.如果您使用的是较旧的节点版本,则npm上还有一个软件包可能会适用.

Works fine on current browsers and latest node. There's also a package on npm that might just work for that if you are working with older node versions.

node-console-group

这会将整个JSON字符串移动3个空格.它将JSON字符串换行,然后在每行的3个空格处添加一个新字符串,以容纳每行移位的内容.

This shifts the whole JSON string by 3 spaces. It breaks the JSON string by new lines, then adds on each line 3 spaces to a new string which will hold every line shifted.

var results = document.getElementById('results');
var obj = {
    a: 5,
    b: 3,
    c: 4
};

var string = JSON.stringify(obj, null, 2);

var stringShifted = '';
string.split('\n').forEach(function(line){
    stringShifted += '   ' + line + '\n';
});
console.log(string);
console.log(stringShifted);

results.innerHTML = 'Before : \n' + string;
results.innerHTML += '\n\nAfter : \n' + stringShifted;

<pre id="results"></pre>

这篇关于NodeJS中缩进的多行日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆