作者:张心虚要加油 | 来源:互联网 | 2020-11-23 17:35
你是否有过这样的经历,当把logging添加到自定义Node模块中,并认为自己将会从这些额外信息中受益,却发现当你将模块添加为依赖项并运行npminstall和npmstart时,你的程序日志就会像下面吗?
我们想要什么
理想的日志记录方案能够使模块日志不进入程序或服务的日志记录,但能够在需要时将其打开以进行故障排除。
为此,我将向你展示如何使用 debug 模块来打开或关闭 Node 模块中的日志。
如果你不需要它们,并且使用该模块的服务运行良好,则将其设置为 OFF。
ON 用于遇到问题并需要尽可能多的日志信息时。
debug
模块概述
在功能方面,请不要像通常在调试器中那样来考虑调试模块(就像你在 ID E中设置断点的方式一样),而应更像是被修改后的 console
模块。这是一种可让你根据需要打开和关闭日志的工具。如果到其 GitHub页面(https://github.com/visionmedi...),则还会看到它的其他各种功能,例如命名空间等。暂时不用管这些,现在只需要知道它是一种可以优化你的生产环境的工具即可。
在你自己的 Node 模块中实现debug
让我们来看一个在代码中使用 debug
的例子。假设下面是一个模块:
const debug = require('debug');
const log = debug('http:server');
const http = require('http');
const name = 'Demo App for debug module';
log('booting %o', name);
http.createServer((req, res) => {
log(req.method + ' ' + req.url);
res.end('debug example\n');
}).listen(3200, () => {
log('listening');
});
实现 debug
很容易。我们要做的就是 import 或 require 模块,然后创建一个logger —— const log = debug('http:server');
。你只需将特定 logger 的标记或命名空间 ‘http:server‘ 传递给 DEBUG
环境变量,以启用调试功能即可。
启动应用程序时(即导入该模块的程序),你将会像这样去启动它:
DEBUG=http:server node app-entrypoint.js
如果我们希望使用单独的 logger 来切换某些日志怎么办?例如,如果我们只想切换到 error 怎么办?就像创建另一个 logger 一样简单,就像这样:
const debug = require('debug');
const log = debug('http:server');
const errorLogger = debug('http:error'); // create new logger here, passing it a new namespace
const http = require('http');
const name = 'Demo App for debug module';
log('booting %o', name);
http.createServer((req, res) => {
log(req.method + ' ' + req.url);
res.end('hello\n');
// fake an error to demonstrate using debug for http:error namespace
setTimeout(() => {
errorLogger('fake error'); // then call the logger
}, 1000);
}).listen(3200, () => {
log('listening');
});
如下所示将会仅打开错误:
DEBUG=http:error node app-entrypoint.js
而且,当你要记录所有命名空间的日志时(在这种情况下,是 http:server
和 http:error
),只需传递通配符 *
即可。
DEBUG=http:* node app-entrypoint.js
让我们看看这些日志现在是什么样的:
我们可以看到切换标记为 “express”,因此 express:*
将为我们提供所有的日志,express:view
将为我们提供视图的日志,等等。
总结
希望你看到在 node 模块中实现 debug
并为第三方模块打开它是多么容易,以及它可以怎样帮你清理日志,同时又为你提供了一种方便的方法来将其重新打开进行故障排除。
更多编程相关知识,请访问:编程课程!!
以上就是避免Node.js模块日志污染程序日志的方法介绍的详细内容,更多请关注 第一PHP社区 其它相关文章!