要定制 Ubuntu 上的 Node.js 應用程序的日志格式,您可以使用以下方法:
winston
和 bunyan
。這些庫提供了豐富的配置選項,可以讓您自定義日志的輸出格式。以 winston
為例,首先安裝它:
npm install winston
然后,在您的 Node.js 應用程序中設置自定義日志格式:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ timestamp, level, message }) => {
return `[${timestamp}] ${level.toUpperCase()}: ${message}`;
})
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/combined.log' }),
],
});
logger.info('Hello, world!');
在這個例子中,我們使用了 winston.format.combine
方法來組合多個格式化選項。winston.format.timestamp()
添加了時間戳,winston.format.printf()
定義了自定義的日志格式。
console
模塊:雖然 console
模塊的定制選項有限,但您仍然可以使用一些簡單的字符串操作來自定義日志輸出格式。例如:
function log(message, level) {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] [${level.toUpperCase()}]: ${message}`);
}
log('Hello, world!', 'info');
這個簡單的 log
函數接受一個消息和一個日志級別,并使用自定義格式輸出日志。
注意:這些示例適用于任何基于 Node.js 的應用程序,不僅僅是 Ubuntu 系統上的應用程序。