在Debian系统上分析Node.js应用程序的网络请求日志,可以通过以下几种方法和工具进行:
使用Morgan中间件记录HTTP请求日志:
npm install morgan
const express = require('express');
const morgan = require('morgan');
const app = express();
// 使用morgan中间件,预定义格式为'tiny'
app.use(morgan('tiny'));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
自定义日志格式:
app.use(morgan('method url status res[content-length] - response-time ms'));
使用Koa中间件记录响应时间:
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
let stime = new Date().getTime(); // 记录当前时间戳
await next(); // 事件控制权中转
let etime = new Date().getTime(); // 所有中间件执行完成后记录当前时间
console.log(`请求地址: ${ctx.path} ,响应时间: ${etime - stime} ms`);
});
app.use(async (ctx, next) => {
console.log('中间件 doSomething');
await next();
console.log('中间件执行 over');
});
app.listen(3000, () => {
console.log('server is running at http://localhost:3000');
});
使用Winston记录日志:
const winston = require('winston');
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' }),
],
});
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const responseTime = Date.now() - start;
logger.info({ req: req.method, reqUrl: req.url, res: res.statusCode, responseTime: responseTime + ' ms' });
});
next();
});
使用ELK(Elasticsearch, Logstash, Kibana)堆栈进行日志采集和分析:
使用Wireshark图形化工具分析网络数据包:
通过上述方法,可以有效地记录和分析Node.js应用中的网络请求日志,帮助开发者监控和优化应用性能。