const fs = require('fs');
const path = require('path');
// Default configuration
const defaultConfig = {
logLevel: 'info', // 'debug', 'info', 'warn', 'error'
logFilePath: 'http_request_log.txt',
includePaths: ['/api/*'], // Paths to include in logging
};
let config = defaultConfig;
// Load configuration from file
try {
const configFilePath = path.join(__dirname, 'config.json');
if (fs.existsSync(configFilePath)) {
const configData = require(configFilePath);
config = { ...defaultConfig, ...configData }; // Merge configs
}
} catch (err) {
console.warn('Failed to load config.json, using default config.');
}
// Function to log HTTP requests
function logHttpRequest(url, method, headers, body, status, startTime, endTime) {
const logMessage = `[${new Date().toISOString()}] ${method} ${url} Status: ${status} Time: ${endTime - startTime}ms`;
if (config.logLevel === 'debug') {
console.debug(logMessage); // Log to console for debug level
} else if (config.logLevel === 'info') {
fs.appendFile(config.logFilePath, logMessage + '\n', (err) => {
if (err) {
console.error('Error writing to log file:', err);
}
});
} else if (config.logLevel === 'warn') {
console.warn(logMessage);
} else if (config.logLevel === 'error') {
console.error(logMessage);
}
}
// Example usage (replace with your actual HTTP request handling)
const http = require('http');
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
const headers = req.headers;
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
const startTime = Date.now();
//Check if the path is in includePaths
if(config.includePaths.some(includePath => url.startsWith(includePath))){
logHttpRequest(url, method, headers, body, res.statusCode, startTime, Date.now());
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
});
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
Add your comment