JAVASCRIPT
Implement Centralized Security Event Logging
Enhance application security and incident response by logging critical security events such as failed logins, access attempts, and sensitive data modifications in Node.js.
// Install: npm install winston
const winston = require('winston');
// Configure Winston logger for security events
const securityLogger = winston.createLogger({
level: 'info', // Log level (e.g., 'info', 'warn', 'error')
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json() // Use JSON format for easier parsing by log analysis tools
),
transports: [
// Console transport for development
new winston.transports.Console({
format: winston.format.simple() // Simpler format for console readability
}),
// File transport for production (important for auditing)
new winston.transports.File({
filename: 'logs/security.log',
level: 'info', // Only write 'info' and above to this file
maxsize: 5 * 1024 * 1024, // 5MB
maxFiles: 5, // Keep 5 log files
tailable: true // Start reading from end if file exists
}),
// Optional: Add a transport for a SIEM (Security Information and Event Management) system
// e.g., new winston.transports.Http or custom transport
],
// Exit process on error by default
exitOnError: false,
});
// Function to log a security event
function logSecurityEvent(type, message, details = {}) {
securityLogger.info({
type: type,
message: message,
...details,
timestamp: new Date().toISOString() // Explicit timestamp for consistency
});
}
// Example usage:
/*
// In your user authentication module:
function handleLogin(username, passwordAttempt) {
if (passwordAttempt === "correctPassword") {
logSecurityEvent('UserLoginSuccess', 'User authenticated successfully', { username: username, ipAddress: '192.168.1.100' });
return true;
} else {
logSecurityEvent('UserLoginFailure', 'Failed login attempt', { username: username, ipAddress: '192.168.1.100', reason: 'InvalidCredentials' });
return false;
}
}
// In an access control module:...
function checkAdminAccess(userId, resource) {
if (userId !== 'admin') {
logSecurityEvent('UnauthorizedAccess', 'Attempt to access admin resource without permission', { userId: userId, resource: resource, ipAddress: '192.168.1.101' });
return false;
}
return true;
}
handleLogin('testuser', 'correctPassword');
handleLogin('testuser', 'wrongPassword');
checkAdminAccess('regularUser', '/admin/settings');
*/
How it works: This snippet demonstrates how to implement centralized security event logging using the `winston` library in Node.js. It configures a dedicated logger to capture critical security events, such as successful/failed login attempts, unauthorized access, or sensitive data modifications. Logs are formatted as JSON for easy parsing by monitoring tools and can be written to both the console (for development) and a dedicated log file (for auditing and forensics). Robust security logging is essential for detecting attacks, investigating incidents, and fulfilling compliance requirements.