1. const fs = require('fs');
  2. const path = require('path');
  3. // Default configuration
  4. const defaultConfig = {
  5. logLevel: 'info', // 'debug', 'info', 'warn', 'error'
  6. logFilePath: 'http_request_log.txt',
  7. includePaths: ['/api/*'], // Paths to include in logging
  8. };
  9. let config = defaultConfig;
  10. // Load configuration from file
  11. try {
  12. const configFilePath = path.join(__dirname, 'config.json');
  13. if (fs.existsSync(configFilePath)) {
  14. const configData = require(configFilePath);
  15. config = { ...defaultConfig, ...configData }; // Merge configs
  16. }
  17. } catch (err) {
  18. console.warn('Failed to load config.json, using default config.');
  19. }
  20. // Function to log HTTP requests
  21. function logHttpRequest(url, method, headers, body, status, startTime, endTime) {
  22. const logMessage = `[${new Date().toISOString()}] ${method} ${url} Status: ${status} Time: ${endTime - startTime}ms`;
  23. if (config.logLevel === 'debug') {
  24. console.debug(logMessage); // Log to console for debug level
  25. } else if (config.logLevel === 'info') {
  26. fs.appendFile(config.logFilePath, logMessage + '\n', (err) => {
  27. if (err) {
  28. console.error('Error writing to log file:', err);
  29. }
  30. });
  31. } else if (config.logLevel === 'warn') {
  32. console.warn(logMessage);
  33. } else if (config.logLevel === 'error') {
  34. console.error(logMessage);
  35. }
  36. }
  37. // Example usage (replace with your actual HTTP request handling)
  38. const http = require('http');
  39. const server = http.createServer((req, res) => {
  40. const url = req.url;
  41. const method = req.method;
  42. const headers = req.headers;
  43. let body = '';
  44. req.on('data', (chunk) => {
  45. body += chunk;
  46. });
  47. req.on('end', () => {
  48. const startTime = Date.now();
  49. //Check if the path is in includePaths
  50. if(config.includePaths.some(includePath => url.startsWith(includePath))){
  51. logHttpRequest(url, method, headers, body, res.statusCode, startTime, Date.now());
  52. }
  53. res.writeHead(200, { 'Content-Type': 'text/plain' });
  54. res.end('Hello, World!\n');
  55. });
  56. });
  57. server.listen(3000, () => {
  58. console.log('Server listening on port 3000');
  59. });

Add your comment