作为IT工程师,定位Node.js接口问题需要系统性地分析日志。以下是详细的解决方案:
const winston = require('winston');
const { combine, timestamp, printf } = winston.format;
const logger = winston.createLogger({
level: 'info',
format: combine(
timestamp(),
printf(({ level, message, timestamp }) => {
return `${timestamp} [${level.toUpperCase()}] ${message}`;
})
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' }),
new winston.transports.File({
filename: 'errors.log',
level: 'error'
})
]
});
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
logger.info(`${req.method} ${req.originalUrl} ${res.statusCode} - ${duration}ms`);
});
next();
});
logger.debug(`Request headers: ${JSON.stringify(req.headers)}`);
logger.debug(`Request body: ${JSON.stringify(req.body)}`);
logger.debug(`Query params: ${JSON.stringify(req.query)}`);
app.use((err, req, res, next) => {
logger.error(`Error occurred: ${err.stack}`);
res.status(500).json({ error: 'Internal Server Error' });
});
# 查找特定接口的日志
grep "GET /api/users" app.log
# 查找错误日志
grep "ERROR" errors.log
# 查找慢请求(超过500ms)
grep " - [0-9]{4,}ms" app.log
const { v4: uuidv4 } = require('uuid');
app.use((req, res, next) => {
req.requestId = uuidv4();
logger.info(`[${req.requestId}] Started ${req.method} ${req.url}`);
next();
});
logger.info({
message: 'API request',
method: req.method,
url: req.url,
status: res.statusCode,
duration: duration,
ip: req.ip,
userAgent: req.headers['user-agent']
});
console.time('databaseQuery');
// 数据库操作
console.timeEnd('databaseQuery');
日志管理工具:
APM工具:
错误监控:
接口返回500错误:
接口响应慢:
接口返回错误数据:
通过系统性地记录和分析日志,可以高效定位Node.js接口问题。建议结合日志级别、请求追踪和结构化日志,建立完整的可观测性体系。