在Debian上使用Node.js自定義日志格式,通常涉及以下幾個步驟:
選擇日志庫:選擇一個適合的日志庫,如 winston
、morgan
或 pino
。這些庫提供了靈活的配置選項來自定義日志格式。
安裝日志庫:使用npm或yarn安裝所選的日志庫。
配置日志格式:根據所選庫的文檔,配置日志格式。
以下是使用 winston
和 morgan
的示例:
安裝 Winston:
npm install winston
配置 Winston:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss'
}),
winston.format.printf(({ timestamp, level, message }) => {
return `${timestamp} ${level}: ${message}`;
})
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
logger.info('Hello, world!');
安裝 Morgan:
npm install morgan
配置 Morgan:
const express = require('express');
const morgan = require('morgan');
const app = express();
// 自定義 Morgan 日志格式
morgan.token('customFormat', (req, res) => {
return `${req.method} ${req.url} - ${res.statusCode}`;
});
app.use(morgan('customFormat'));
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
根據你的具體需求選擇合適的日志庫,并按照其文檔進行配置即可。