2025-09-24 17:11:35 +09:00
|
|
|
const { saveApiLog } = require('../database/log-queries');
|
|
|
|
|
|
|
|
|
|
// API 로그 미들웨어
|
|
|
|
|
function apiLogger(req, res, next) {
|
|
|
|
|
const startTime = Date.now();
|
|
|
|
|
|
|
|
|
|
// 원본 res.end 함수 저장
|
|
|
|
|
const originalEnd = res.end;
|
|
|
|
|
|
|
|
|
|
// res.end 함수 오버라이드
|
|
|
|
|
res.end = function(chunk, encoding) {
|
|
|
|
|
const endTime = Date.now();
|
|
|
|
|
const responseTime = endTime - startTime;
|
|
|
|
|
|
|
|
|
|
// 로그 데이터 수집
|
|
|
|
|
const logData = {
|
|
|
|
|
method: req.method,
|
|
|
|
|
endpoint: req.originalUrl || req.url,
|
|
|
|
|
requestBody: req.body,
|
|
|
|
|
responseStatus: res.statusCode,
|
|
|
|
|
responseTime: responseTime,
|
|
|
|
|
ipAddress: req.ip || req.connection.remoteAddress || req.socket.remoteAddress,
|
|
|
|
|
userAgent: req.get('User-Agent') || null
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// 인증된 사용자 정보가 있으면 추가
|
|
|
|
|
if (req.user) {
|
|
|
|
|
logData.userId = req.user.id;
|
|
|
|
|
logData.username = req.user.username;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// API 키 정보가 있으면 추가
|
|
|
|
|
if (req.apiKey) {
|
|
|
|
|
logData.apiKeyId = req.apiKey.id;
|
2025-09-25 16:23:32 +09:00
|
|
|
logData.apiKeyName = req.apiKey.keyName;
|
2025-09-24 17:11:35 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 비동기로 로그 저장 (응답 속도에 영향 주지 않도록)
|
|
|
|
|
saveApiLog(logData).catch(error => {
|
|
|
|
|
console.error('API 로그 저장 중 오류:', error);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// 원본 res.end 호출
|
|
|
|
|
originalEnd.call(this, chunk, encoding);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
next();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 특정 경로 제외 미들웨어
|
|
|
|
|
function skipLogging(paths = []) {
|
|
|
|
|
return (req, res, next) => {
|
|
|
|
|
const shouldSkip = paths.some(path => {
|
|
|
|
|
if (typeof path === 'string') {
|
|
|
|
|
return req.path === path;
|
|
|
|
|
} else if (path instanceof RegExp) {
|
|
|
|
|
return path.test(req.path);
|
|
|
|
|
}
|
|
|
|
|
return false;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (shouldSkip) {
|
|
|
|
|
return next();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return apiLogger(req, res, next);
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
|
apiLogger,
|
|
|
|
|
skipLogging
|
|
|
|
|
};
|