在Debian系統中,Node.js應用程序通常使用console.log()
或第三方日志庫(如winston
、morgan
等)來記錄日志。要自定義Node.js的日志格式,你可以根據所使用的日志庫進行相應的配置。
以下是一些常見日志庫的自定義日志格式方法:
console.log()
:console.log()
默認輸出格式有限,但你可以通過自定義格式化字符串來實現一定程度的自定義。例如:
const timestamp = new Date().toISOString();
const message = 'Hello, World!';
console.log(`${timestamp} - ${message}`);
winston
庫:首先,安裝winston
庫:
npm install winston
然后,在你的Node.js應用程序中配置winston
:
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!');
morgan
庫:首先,安裝morgan
庫:
npm install morgan
然后,在你的Node.js應用程序中配置morgan
:
const express = require('express');
const morgan = require('morgan');
const app = express();
const morganFormat = ':method :url :status :res[content-length] - :response-time ms - :message';
app.use(morgan(morganFormat));
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000);
這些示例僅展示了如何自定義日志格式。你可以根據自己的需求進行調整。在實際應用中,你可能需要記錄更多的信息,例如請求頭、響應頭等。你可以查閱相關文檔以獲取更多關于自定義日志格式的信息。