要減少Node.js日志輸出,您可以采取以下幾種方法:
例如,使用winston庫設置日志級別:
const winston = require('winston');
const logger = winston.createLogger({
level: 'warn', // 設置日志級別為warn,只顯示warn、error級別的日志
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
],
});
例如,使用winston庫設置日志文件大小和數量限制:
const winston = require('winston');
const { combine, timestamp, printf } = winston.format;
const myFormat = printf(({ level, message, timestamp }) => {
return `${timestamp} ${level.toUpperCase()}: ${message}`;
});
const logger = winston.createLogger({
level: 'info',
format: combine(timestamp(), myFormat),
transports: [
new winston.transports.File({ filename: 'combined.log', maxsize: 200000, maxFiles: 3 }),
],
});
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' }),
],
});
if (process.env.NODE_ENV === 'production') {
logger.level = 'warn'; // 在生產環境中,只顯示warn和error級別的日志
}
通過以上方法,您可以有效地減少Node.js日志輸出,從而提高應用程序的性能和可維護性。