在Ubuntu下,Node.js应用程序的日志级别通常是通过应用程序代码来设置的。大多数Node.js应用程序使用第三方日志库,如winston
、bunyan
或morgan
等。这些库通常允许你设置不同的日志级别,例如:error、warn、info、verbose和debug。
以winston
为例,你可以在应用程序代码中设置日志级别,如下所示:
const winston = require('winston'); const logger = winston.createLogger({ level: 'info', // 设置日志级别 format: winston.format.json(), transports: [ new winston.transports.File({ filename: 'error.log', level: 'error' }), new winston.transports.File({ filename: 'combined.log' }), ], }); // 如果不在生产环境中,可以设置更高的日志级别,例如 'debug' if (process.env.NODE_ENV !== 'production') { logger.level = 'debug'; }
在这个例子中,我们将默认日志级别设置为info
。这意味着只有info
、warn
和error
级别的日志会被记录。我们还将错误日志单独记录到一个名为error.log
的文件中,并将所有级别的日志记录到名为combined.log
的文件中。
如果你想要在运行Node.js应用程序时动态更改日志级别,你可以使用第三方库,如winston-level
。这是一个简单的示例:
const winston = require('winston'); const Level = require('winston-level'); const logger = winston.createLogger({ level: new Level('info'), format: winston.format.json(), transports: [ new winston.transports.File({ filename: 'error.log', level: 'error' }), new winston.transports.File({ filename: 'combined.log' }), ], }); // 在运行时更改日志级别 setTimeout(() => { logger.level = new Level('debug'); }, 10000); // 10秒后将日志级别更改为'debug'
在这个例子中,我们在10秒后将日志级别从info
更改为debug
。这可以帮助你在生产环境中调试问题,而无需重新启动应用程序。