我有这样一个对象:
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
但是当我尝试使用console.log(myObject)显示它时,我收到这样的输出:
{ a: 'a', b: { c: 'c', d: { e: 'e', f: [Object] } } }
我怎样才能得到完整的对象,包括属性f的内容?
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
console.log(JSON.stringify(myObject));
输出:
{"a":"a","b":{"c":"c","d":{"e":"e","f":{"g":"g","h":{"i":"i"}}}}}
您可以简单地向对象添加一个inspect()方法,该方法将覆盖console.log消息中的对象表示
eg:
var myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
myObject.inspect = function(){ return JSON.stringify( this, null, ' ' ); }
然后,您的对象将在console.log和node shell中按要求表示
更新:
对象。Inspect已弃用(https://github.com/nodejs/node/issues/15549)。使用myObject [util.inspect。自定义):
const util = require('util')
var myObject = {
/* nested properties not shown */
}
myObject[util.inspect.custom] = function(){ return JSON.stringify( this, null, 4 ); }
console.log(util.inspect(myObject))
使用记录器
不要试图重新发明轮子
util.inspect(), JSON.stringify()和console.dir()是在浏览器控制台中播放时记录对象的有用工具。
如果你认真对待Node.js开发,你绝对应该使用记录器。使用它,您可以添加调试和监视应用程序所需的所有日志。然后只需更改日志记录器的日志级别,以只显示生产日志。
此外,他们已经解决了所有与日志相关的恼人问题,如:循环对象,格式,日志级别,多个输出和性能。
使用现代的记录器
pino是一个快速和现代的Node.js日志记录器,它有正常的默认值来处理循环对象/引用,如depthLimit和edgeLimit。它支持子日志记录器、传输和漂亮的打印输出。
此外,它有8个默认的日志级别,你可以使用customLevels选项自定义:
致命的
错误
警告
信息
调试
跟踪
沉默
安装它
npm install pino
使用它
const logger = require('pino')()
logger.info('hello world')
配置它
const logger = pino({
depthLimit: 10,
edgeLimit: 200,
customLevels: {
foo: 35
}
});
logger.foo('hi')