在Ubuntu中配置Node.js應用程序的日志輸出可以通過多種方式實現,包括使用內置的console
模塊、第三方日志庫(如winston
或morgan
)以及配置日志輪轉。以下是一些常見的方法:
console
模塊Node.js的內置console
模塊是最簡單的日志輸出方式。你可以使用console.log
、console.error
等方法來輸出日志。
const express = require('express');
const app = express();
app.get('/', (req, res) => {
console.log('Hello World!');
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
winston
是一個功能強大的日志庫,支持多種傳輸方式(如控制臺、文件、HTTP等)。
winston
:npm install winston
winston
:const express = require('express');
const winston = require('winston');
const app = express();
// 創建一個logger實例
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
// 如果不在生產環境中,將日志輸出到控制臺
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
app.get('/', (req, res) => {
logger.info('Hello World!');
res.send('Hello World!');
});
app.listen(3000, () => {
logger.info('Server is running on port 3000');
});
morgan
是一個HTTP請求日志中間件,適用于Express應用程序。
morgan
:npm install morgan
morgan
:const express = require('express');
const morgan = require('morgan');
const app = express();
// 使用morgan中間件
app.use(morgan('combined'));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
為了防止日志文件過大,可以使用winston-daily-rotate-file
庫來實現日志輪轉。
winston-daily-rotate-file
:npm install winston-daily-rotate-file
const express = require('express');
const winston = require('winston');
const { createLogger, format, transports } = winston;
const DailyRotateFile = require('winston-daily-rotate-file');
const app = express();
// 創建一個logger實例
const logger = createLogger({
level: 'info',
format: format.combine(
format.timestamp(),
format.json()
),
transports: [
new transports.Console(),
new DailyRotateFile({
filename: 'application-%DATE%.log',
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
})
]
});
app.get('/', (req, res) => {
logger.info('Hello World!');
res.send('Hello World!');
});
app.listen(3000, () => {
logger.info('Server is running on port 3000');
});
通過這些方法,你可以在Ubuntu中靈活地配置Node.js應用程序的日志輸出。