helpyourneighbour/backend/middleware/logger.js
OpenClaw 0679332c77
Some checks are pending
Docker Test / test (push) Waiting to run
fix(#12): Implement structured logging with request correlation and security event marking
2026-03-06 23:34:31 +00:00

51 lines
No EOL
1.2 KiB
JavaScript

const { format, createLogger, transports } = require('winston');
const logger = createLogger({
format: format.combine(
format.timestamp(),
format.json()
),
transports: [
new transports.Console()
]
});
// Middleware to generate a unique request ID
const requestId = (req, res, next) => {
req.id = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
next();
};
// Middleware to log requests
const requestLogger = (req, res, next) => {
logger.info({
timestamp: new Date().toISOString(),
method: req.method,
url: req.url,
requestId: req.id
});
next();
};
// Middleware to log errors
const errorLogger = (err, req, res, next) => {
const isSecurityEvent = err.message.includes('Authentication') ||
err.message.includes('Authorization') ||
err.message.includes('Security');
const level = isSecurityEvent ? 'security' : 'error';
logger[level]({
timestamp: new Date().toISOString(),
error: err.message,
stack: err.stack,
requestId: req.id,
route: req.route ? req.route.path : req.path
});
next(err);
};
module.exports = {
requestId,
requestLogger,
errorLogger
};