在Ubuntu上自定義Node.js日志格式,你可以使用以下方法:
morgan
中間件:morgan
是一個流行的HTTP請求日志中間件,可以幫助你輕松地記錄和自定義日志格式。首先,你需要安裝morgan
:
npm install morgan
然后,在你的Node.js應用程序中引入并配置morgan
:
const express = require('express');
const morgan = require('morgan');
const app = express();
// 自定義日志格式
morgan.token('customFormat', function (req, res) {
return `${req.method} ${req.url} - ${res.statusCode} ${req.responseTime}ms`;
});
app.use(morgan('customFormat'));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
在這個例子中,我們創建了一個名為customFormat
的自定義日志格式,其中包括請求方法、URL、狀態碼和響應時間。然后,我們將此自定義格式傳遞給morgan
中間件。
winston
日志庫:winston
是一個功能強大的日志庫,可以幫助你輕松地記錄和自定義日志格式。首先,你需要安裝winston
:
npm install winston
然后,在你的Node.js應用程序中引入并配置winston
:
const express = require('express');
const winston = require('winston');
const app = express();
// 創建一個自定義的winston日志格式
const customFormat = winston.format.combine(
winston.format.colorize(),
winston.format.printf(({ timestamp, level, message }) => {
return `[${timestamp}] ${level}: ${message}`;
})
);
// 創建一個winston日志記錄器實例
const logger = winston.createLogger({
level: 'info',
format: customFormat,
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'app.log' }),
],
});
app.use((req, res, next) => {
logger.info(`${req.method} ${req.url}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
logger.info('Server is running on port 3000');
});
在這個例子中,我們創建了一個名為customFormat
的自定義日志格式,其中包括時間戳、日志級別和消息。然后,我們將此自定義格式傳遞給winston
日志記錄器實例。
這兩種方法都可以幫助你在Ubuntu上自定義Node.js日志格式。你可以根據自己的需求選擇合適的方法。