1. const fs = require('fs');
  2. const path = require('path');
  3. const moment = require('moment'); // For timestamping backup files
  4. /**
  5. * Backs up log files to a specified directory.
  6. * @param {string} logDirectory - The directory containing the log files.
  7. * @param {string} backupDirectory - The directory to store the backups.
  8. * @param {number} backupRetentionDays - The number of days to keep backups.
  9. */
  10. function backupLogs(logDirectory, backupDirectory, backupRetentionDays) {
  11. // Ensure backup directory exists
  12. if (!fs.existsSync(backupDirectory)) {
  13. fs.mkdirSync(backupDirectory);
  14. }
  15. const now = moment();
  16. const cutoffDate = now.subtract(backupRetentionDays, 'days').toDate();
  17. // Read files in the log directory
  18. fs.readdir(logDirectory, (err, files) => {
  19. if (err) {
  20. console.error('Error reading log directory:', err);
  21. return;
  22. }
  23. files.forEach(file => {
  24. const filePath = path.join(logDirectory, file);
  25. //Check if it's a file (not a directory)
  26. fs.stat(filePath, (err, stats) => {
  27. if (err) {
  28. console.error('Error getting file stats:', err);
  29. return;
  30. }
  31. if (stats.isFile()) {
  32. // Generate backup filename with timestamp
  33. const timestamp = moment().format('YYYYMMDDHHmmss');
  34. const backupFileName = `backup_${file}_${timestamp}`;
  35. const backupFilePath = path.join(backupDirectory, backupFileName);
  36. try {
  37. // Copy the file to the backup directory
  38. fs.copyFileSync(filePath, backupFilePath);
  39. console.log(`Backed up ${file} to ${backupFilePath}`);
  40. // Optionally, delete backups older than the retention period
  41. const lastModified = stats.mtime;
  42. if (lastModified < cutoffDate) {
  43. fs.unlinkSync(backupFilePath);
  44. console.log(`Deleted old backup ${backupFilePath}`);
  45. }
  46. } catch (copyErr) {
  47. console.error(`Error backing up ${file}:`, copyErr);
  48. }
  49. }
  50. });
  51. });
  52. });
  53. }
  54. // Example Usage (replace with your actual directories and retention period)
  55. const logDirectory = '/path/to/your/logs'; // Replace with your log directory
  56. const backupDirectory = '/path/to/your/backups'; // Replace with your backup directory
  57. const backupRetentionDays = 7; // Keep backups for 7 days
  58. backupLogs(logDirectory, backupDirectory, backupRetentionDays);

Add your comment