NodeJS中如何为console.log输出的变量每行添加2个制表符?
给MongoDB对象日志添加自定义缩进的方法
针对你需要给products变量输出的每一行添加2个制表符的需求,这里提供两种实用的实现方式:
方法1:使用JSON.stringify自定义格式化
适合需要精确控制输出格式的场景,需手动处理MongoDB的ObjectId:
// 在controllers/cart.js中定义格式化函数 const { ObjectId } = require('mongodb'); const formatLog = (label, obj) => { // 处理ObjectId,转换为期望的字符串格式 const replacer = (key, value) => { if (value instanceof ObjectId) { return `new ObjectId("${value.toString()}")`; } return value; }; // 先将对象转为带缩进的JSON字符串,再给每行添加2个制表符 const formattedObj = JSON.stringify(obj, replacer, 4) .replace(/"new ObjectId\("([^"]+)"\)"/g, 'new ObjectId("$1")') // 移除多余引号 .split('\n') .map(line => '\t\t' + line) .join('\n'); return `${label}\n\t\t${formattedObj.replace(/^\t\t/, '')}`; }; // 使用示例 console.log(formatLog('[controllers/cart.js].getProductsInCart', products));
方法2:使用Node.js内置util.inspect
更适配Node.js环境,能自动识别大部分内置对象,仅需少量格式调整:
const util = require('util'); const { ObjectId } = require('mongodb'); // 自定义ObjectId的inspect格式,让输出显示为new ObjectId(...) ObjectId.prototype[util.inspect.custom] = function() { return `new ObjectId("${this.toString()}")`; }; // 格式化日志内容 const formattedProducts = util.inspect(products, { depth: null, // 显示对象所有层级 indentation: 4, // 内部层级缩进4个空格 colors: true // 可选,开启终端彩色输出增强可读性 }) .split('\n') .map(line => '\t\t' + line) .join('\n'); console.log('[controllers/cart.js].getProductsInCart'); console.log(`\t\tproducts = ${formattedProducts.replace(/^\t\t/, '')}`);
两种方法都能输出你期望的格式:
[controllers/cart.js].getProductsInCart products = [ { productId: new ObjectId("645a54116710e60e28b96903"), quantity: 1, _id: new ObjectId("645a6e2e119c195fd8b32f99") } ]
内容的提问来源于stack exchange,提问作者William Le
相关产品推荐
相关产品推荐

