企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
&emsp;&emsp;在 Node.js 中,提供了[console](https://nodejs.org/dist/latest-v18.x/docs/api/console.html)模块,这是一个简单的调试控制台,其功能类似于浏览器提供的 JavaScript 控制台。 &emsp;&emsp;本系列所有的示例源码都已上传至Github,[点击此处](https://github.com/pwstrick/node)获取。  ## 一、原理 &emsp;&emsp;与浏览器一样,Node.js 也提供了一个全局变量 console(实例化 Console 类),可调用 log()、error() 等方法。 **1)同步还是异步** &emsp;&emsp;console 的方法既不像浏览器中那样始终同步,也不像 Node.js 中的流那样始终异步。 &emsp;&emsp;是否为同步取决于链接的是什么流以及操作系统是 Windows 还是 POSIX: * 文件:在 Windows 和 POSIX 中都是同步。 * TTY(终端):在 Windows 上是异步,在 POSIX 上是同步。 * 管道和套接字:在 Windows 上是同步,在 POSIX 上是异步。 &emsp;&emsp;可移植操作系统接口(Portable Operating System Interface,缩写为POSIX)是 IEEE 为要在各种 UNIX 操作系统上运行软件,而定义API的一系列互相关联的标准的总称。 &emsp;&emsp;console 的这些行为部分是出于历史原因,因为一旦将它们更改,那么会导致向后不兼容(即不兼容旧版本)。 &emsp;&emsp;注意,同步写入会阻塞事件循环,直至写入完成。 &emsp;&emsp;在输出到文件的情况下,这可能几乎是瞬时的。 &emsp;&emsp;但在系统负载高、接收端未读取管道或终端或文件系统速度较慢的情况下,事件循环可能经常被阻塞足够长,足以对性能产生严重的负面影响。 **2)log() 和 error()** &emsp;&emsp;在[src/lib/internal/console/constructor.js](https://github.com/nodejs/node/blob/master/lib/internal/console/constructor.js)中,存储着 console.log() 和 console.error() 两个方法的源码。 &emsp;&emsp;下面是删减过的源码,可以看到在输出之前会自动加换行符,并且 log() 和 error() 使用的输出方法还不同。 ~~~ function(streamSymbol, string) { const groupIndent = this[kGroupIndent]; const useStdout = streamSymbol === kUseStdout; // 若是普通输出,则用 process.stdout 输出,若是错误,则用 process.stderr 输出 const stream = useStdout ? this._stdout : this._stderr; const errorHandler = useStdout ? this._stdoutErrorHandler : this._stderrErrorHandler; if (groupIndent.length !== 0) { if (StringPrototypeIncludes(string, "\n")) { string = StringPrototypeReplace(string, /\n/g, `\n${groupIndent}`); } string = groupIndent + string; } // 末尾加换行 string += "\n"; try { // 控制台输出 stream.write(string, errorHandler); } catch (e) { // Console is a debugging utility, so it swallowing errors is not // desirable even in edge cases such as low stack space. if (isStackOverflowError(e)) throw e; // Sorry, there's no proper way to pass along the error here. } finally { stream.removeListener("error", noop); } } ~~~ &emsp;&emsp;若是 log() 输出,则用 process.stdout.write() 方法;若是 error() 输出,则用 process.stderr.write() 方法。 &emsp;&emsp;process.stdout 返回的是一个流,配合 util 模块的[inspect()](https://nodejs.org/dist/latest-v18.x/docs/api/util.html#utilinspectobject-options)方法,可将对象解析成字符串,并在控制台着色,如下所示。 ~~~ const util = require('util'); const str = util.inspect({ name: "strick" }, { colors: true }); process.stdout.write(str +'\n'); ~~~ :-: ![](https://img.kancloud.cn/61/0e/610e8eb9577b7c6e079a502600d184b9_576x62.png) ## 二、bunyan.js &emsp;&emsp;目前在我们的项目中,使用的日志库是[bunyan.js](https://github.com/trentm/node-bunyan),这个库不仅支持终端和 Node.js 环境,还支持浏览器环境。 **1)原理** &emsp;&emsp;从 Github 上下载源码后,可以看到 bin 和 lib 两个目录,终端的代码存于前者,项目中引用的代码存于后者。 &emsp;&emsp;下面是一个简单的示例,引入后也不用实例化,可直接调用方法,log.info() 相当于 console.log(),不过前者会自动将对象转换成字符串。 ~~~ const bunyan = require('bunyan'); const log = bunyan.createLogger({name: "example"}); log.info("strick"); ~~~ &emsp;&emsp;在日志内部,会为每条日志维护一个对象,像上面的 strick 字符串,在内部生成的对象格式如下。 ~~~ { name: 'example', hostname: '192.168.0.101', pid: 94371, level: 30, msg: 'strick', time: 2022-05-11T07:21:51.310Z, v: 0 } ~~~ &emsp;&emsp;下面是日志输出的核心代码(已做删减),其中 s.stream 使用的也是 process.stdout 类。 &emsp;&emsp;fastAndSafeJsonStringify() 函数用于将对象转换成字符串,它的工作原理会在后文分析。 ~~~ Logger.prototype._emit = function (rec, noemit) { var i; // 将对象转换成字符串 var str; if (noemit || this.haveNonRawStreams) { str = fastAndSafeJsonStringify(rec) + os.EOL; } if (noemit) return str; var level = rec.level; for (i = 0; i < this.streams.length; i++) { var s = this.streams[i]; if (s.level <= level) { // 输出原始对象或字符串 s.stream.write(s.raw ? rec : str); } } return str; }; ~~~ &emsp;&emsp;默认运行 node src.js,在控制台输出时是没有着色的,不便于阅读。 &emsp;&emsp;在本地调试 bunyan 库时,可以加 node src.js | ../bin/bunyan,执行此命令后,不仅能着色,还会格式化成可读性更高的字符串,如下所示。 :-: ![](https://img.kancloud.cn/84/0b/840bf3c9057585be0cb586557f3f4919_1820x116.png =800x) &emsp;&emsp;注意,在项目中加载此库后,命令中就不需要加路径了,例如 node index.js | bunyan。 **2)fastAndSafeJsonStringify()** &emsp;&emsp;此函数会在 JSON 对象序列化时,处理对象中的循环和 getter 异常,如下所示。 &emsp;&emsp;第一组 try-catch 用于处理[JSON.stringify()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)的异常,第二组 try-catch 用于处理 JSON.stringify(rec, safeCycles()) 的异常。 &emsp;&emsp;最后会判断是否安装了[safe-json-stringify](https://github.com/debitoor/safe-json-stringify)库,若安装就用该库处理,否则就输出报错信息。 ~~~ function fastAndSafeJsonStringify(rec) { try { return JSON.stringify(rec); } catch (ex) { try { return JSON.stringify(rec, safeCycles()); } catch (e) { // 安装了 safe-json-stringify 库 if (safeJsonStringify) { return safeJsonStringify(rec); } else { var dedupKey = e.stack.split(/\n/g, 3).join("\n"); _warn( "bunyan: ERROR: Exception in " + "`JSON.stringify(rec)`. You can install the " + '"safe-json-stringify" module to have Bunyan fallback ' + "to safer stringification. Record:\n" + _indent(format("%s\n%s", util.inspect(rec), e.stack)), dedupKey ); return format( "(Exception in JSON.stringify(rec): %j. " + "See stderr for details.)", e.message ); } } } } ~~~ &emsp;&emsp;接下来看一个循环引用的例子,如下所示,在调用 JSON.stringify() 方法时会报错:TypeError: Converting circular structure to JSON。 &emsp;&emsp;一般自己写的 JSON 对象很少会出现循环引用,但是在一些比较复杂的对象内部有可能会出现。 ~~~ const man = { child: {} } man.child = man; JSON.stringify(man); ~~~ &emsp;&emsp;在 bunyan.js 的内部给出了两种解决方案,一种是用[Set](https://www.kancloud.cn/pwstrick/fe-questions/1094987)数据类型处理,另一种是用数组处理。 &emsp;&emsp;解决思路其实差不多,都是依次将属性值加到数据结构中,当判断到已存在时,就返回 \[Circular\],终止其后面属性的序列化。 ~~~ var safeCycles = typeof (Set) !== 'undefined' ? safeCyclesSet : safeCyclesArray; // Set 方式 function safeCyclesSet() { var seen = new Set(); return function (key, val) { // 若 value 不存在或不是对象类型,则返回该值 if (!val || typeof val !== "object") { return val; } // 若 seen 中包含该值,则返回 [Circular] if (seen.has(val)) { return "[Circular]"; } seen.add(val); return val; }; } // 数组方式 function safeCyclesArray() { var seen = []; return function (key, val) { if (!val || typeof val !== "object") { return val; } if (seen.indexOf(val) !== -1) { return "[Circular]"; } seen.push(val); return val; }; } ~~~ &emsp;&emsp;JSON.stringify() 方法的第二个参数是一个回调,被序列化的值的每个属性都会经过该函数的处理。 &emsp;&emsp;在调用 safeCyclesSet() 函数后,就能输出 {"child":"\[Circular\]"}。 ~~~ JSON.stringify(man, safeCyclesSet()); // {"child":"[Circular]"} ~~~ 参考资料: [日志模块](https://www.nodejs.red/#/nodejs/console) [process对象](https://javascript.ruanyifeng.com/nodejs/process.html) [官网 process](https://nodejs.org/dist/latest-v18.x/docs/api/process.html#a-note-on-process-io) [console](https://nodejs.org/dist/latest-v18.x/docs/api/console.html) ***** > 原文出处: [博客园-Node.js精进](https://www.cnblogs.com/strick/category/2154090.html) [知乎专栏-前端性能精进](https://www.zhihu.com/column/c_1611672656142725120) 已建立一个微信前端交流群,如要进群,请先加微信号freedom20180706或扫描下面的二维码,请求中需注明“看云加群”,在通过请求后就会把你拉进来。还搜集整理了一套[面试资料](https://github.com/pwstrick/daily),欢迎浏览。 ![](https://box.kancloud.cn/2e1f8ecf9512ecdd2fcaae8250e7d48a_430x430.jpg =200x200) 推荐一款前端监控脚本:[shin-monitor](https://github.com/pwstrick/shin-monitor),不仅能监控前端的错误、通信、打印等行为,还能计算各类性能参数,包括 FMP、LCP、FP 等。