在Ubuntu系統中,為Node.js應用程序設置日志時間戳可以通過多種方式實現。以下是幾種常見的方法:
morgan中間件morgan是一個流行的HTTP請求日志中間件,可以為Node.js應用程序添加時間戳。
安裝morgan:
npm install morgan
在你的Node.js應用程序中使用morgan:
const express = require('express');
const morgan = require('morgan');
const app = express();
// 使用morgan中間件,并設置格式為自定義格式,包含時間戳
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
winston日志庫winston是一個功能強大的日志庫,可以輕松地為日志添加時間戳。
安裝winston:
npm install winston
配置winston以添加時間戳:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(), // 添加時間戳
winston.format.json() // 可選:將日志格式化為JSON
),
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!');
如果你不想使用第三方庫,也可以手動為日志添加時間戳。
const fs = require('fs');
const http = require('http');
const server = http.createServer((req, res) => {
const timestamp = new Date().toISOString();
const logEntry = `${timestamp} - ${req.method} ${req.url}\n`;
fs.appendFile('access.log', logEntry, (err) => {
if (err) throw err;
});
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!\n');
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
morgan和自定義格式如果你使用morgan并且想要自定義日志格式,可以這樣做:
const express = require('express');
const morgan = require('morgan');
const app = express();
// 自定義morgan格式,包含時間戳
morgan.token('timestamp', () => new Date().toISOString());
app.use(morgan(':timestamp :method :url :status :res[content-length] - :response-time ms'));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
通過這些方法,你可以在Ubuntu系統中的Node.js應用程序中輕松地添加時間戳到日志中。選擇適合你項目需求的方法即可。