因此,我想禁用 Node.JS 应用程序 (Express) 的某些环境的日志记录;以下是在 Node.JS 应用程序中禁用日志记录的最佳方法吗?
if(process.env.NODE_ENV == "production")
{
console.log = function(){};
}
在我的 app.js 中添加这段代码是否也会影响所有中间件和路由(我想禁用整个应用程序、路由、中间件等的日志记录)?
Thanks
您可能想搬离console.log
并使用日志库,例如winston https://github.com/winstonjs/winston,但这取决于您的项目有多大以及您想要多大的灵活性。
顺便一提console.log = function() {};
会起作用,这仅取决于您是否希望某些日志记录起作用(可能是这种情况,您可能希望看到错误)。
我通过创建以下设置来测试前一个:
文件1.js
console.log = function() {};
require('./2');
文件2.js
// you will not see anything
console.log(2);
如果您决定使用它,您将能够设置日志记录级别 https://github.com/winstonjs/winston#logging-levels,这将帮助您不在生产环境中显示详细日志。
例如:
var winston = require('winston');
winston.level = process.env.NODE_ENV == 'production' ? 'error' : 'debug';
// will show 'ERROR' in production logs
winston.error('ERROR')
// will show 'called test function' in an environment
// different from production
winston.debug('called test function')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)