禁用登录 Node.JS

Disable logging in Node.JS

所以我想为我的 Node.JS 应用程序 (Express) 的某些环境禁用日志记录;以下是禁用登录 Node.JS 应用程序的最佳方法吗?

if(process.env.NODE_ENV == "production")
{
    console.log = function(){}; 
}

在我的 app.js 中添加这段代码是否也会影响所有中间件和路由(我想禁用整个应用程序、路由、中间件...的日志记录)?

谢谢

您可能想离开 console.log 并使用诸如 winston 之类的日志库,但这取决于您的项目有多大以及您想要多大的灵活性。

顺便说一下,console.log = function() {}; 会起作用,这取决于您是否希望某些日志记录起作用(可能是这种情况,您可能希望看到错误)。

我已经通过创建以下设置测试了之前的设置:

文件1.js

console.log = function() {};
require('./2');

文件2.js

// you will not see anything
console.log(2);

如果您决定使用它,您将能够设置 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')