在Ubuntu中,可以使用morgan
和winston
這兩個流行的日志庫來格式化Node.js應用程序的日志。下面是如何在這兩個庫中設置日志格式的方法。
首先,通過npm安裝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}`;
});
app.use(morgan('customFormat'));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
在這個例子中,我們創建了一個自定義的日志格式,包括請求方法、URL和狀態碼。
首先,通過npm安裝winston:
npm install winston
然后,在你的Node.js應用程序中引入并配置winston:
const express = require('express');
const winston = require('winston');
const app = express();
// 創建一個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/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');
});
在這個例子中,我們使用winston創建了一個自定義的日志格式,包括時間戳、日志級別和消息。同時,我們將日志輸出到控制臺和一個名為app.log
的文件中。
這兩種方法都可以幫助你在Ubuntu中格式化Node.js應用程序的日志。你可以根據自己的需求選擇合適的方法。