You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.2 KiB
52 lines
1.2 KiB
import { Request, Response, NextFunction } from 'express';
|
|
import logger from '../utils/logger';
|
|
|
|
// 请求日志中间件
|
|
export function requestLogger(req: Request, res: Response, next: NextFunction): void {
|
|
const start = Date.now();
|
|
|
|
res.on('finish', () => {
|
|
const duration = Date.now() - start;
|
|
const logData = {
|
|
method: req.method,
|
|
url: req.url,
|
|
status: res.statusCode,
|
|
duration: `${duration}ms`,
|
|
ip: req.ip,
|
|
userAgent: req.get('user-agent'),
|
|
userId: req.user?.id,
|
|
};
|
|
|
|
if (res.statusCode >= 400) {
|
|
logger.warn('HTTP Request', logData);
|
|
} else {
|
|
logger.info('HTTP Request', logData);
|
|
}
|
|
});
|
|
|
|
next();
|
|
}
|
|
|
|
// 慢请求警告中间件
|
|
export function slowRequestLogger(threshold: number = 1000) {
|
|
return (req: Request, res: Response, next: NextFunction) => {
|
|
const start = Date.now();
|
|
|
|
res.on('finish', () => {
|
|
const duration = Date.now() - start;
|
|
|
|
if (duration > threshold) {
|
|
logger.warn('Slow Request', {
|
|
method: req.method,
|
|
url: req.url,
|
|
duration: `${duration}ms`,
|
|
threshold: `${threshold}ms`,
|
|
ip: req.ip,
|
|
});
|
|
}
|
|
});
|
|
|
|
next();
|
|
};
|
|
}
|