Guest User

Untitled

a guest
Aug 21st, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. #!/usr/bin/env php
  2. <?php
  3. /* This script is designed to delete logs files if it exceeds a defined size limit.
  4. * Size limit is applied to all log files, instead of individual file.
  5. * The logs are sorted by filename in reversed alphabetical order.
  6. * Each file's size is counted and sum with previous file. If size limit is exceeded,
  7. * subsequent files are deleted.
  8. */
  9.  
  10. const MB = 1024 * 1024;
  11.  
  12. /** CONFIGURATIONS **/
  13.  
  14. /* State your configurations here.
  15. * - limit: Size in bytes.
  16. * - path: Absolute path to folder containing log files.
  17. * - prefix: Log filename prefix.
  18. */
  19. $logs = [
  20. ['limit' => 700 * MB, 'path' => '/path/to/application/logs', 'prefix' => 'log-'],
  21. ['limit' => 100 * MB, 'path' => '/path/to/another/log', 'prefix' => 'example-'],
  22. ];
  23.  
  24. /** CODE **/
  25.  
  26. /**
  27. * Send message to STDOUT.
  28. * @param string $message
  29. */
  30. function logInfo($message) {
  31. fwrite(STDOUT, date('Y-m-d H:i:s')." {$message}".PHP_EOL);
  32. }
  33.  
  34. /**
  35. * Send message to STDERR
  36. * @param string $message
  37. */
  38. function logError($message) {
  39. fwrite(STDERR, date('Y-m-d H:i:s')." {$message}".PHP_EOL);
  40. }
  41.  
  42. /**
  43. * Check total file size and delete files.
  44. * @param string $path Folder path containing log files
  45. * @param string $prefix Log filename prefix
  46. * @param int $limit Size limit in bytes
  47. */
  48. function processFolder($path, $prefix, $limit) {
  49. $path = rtrim($path, '/').'/';
  50.  
  51. $totalSize = 0;
  52. // This sorting **assumes** filename contain timestamp
  53. foreach (array_reverse(glob("{$path}{$prefix}*")) as $filename) {
  54. $totalSize += filesize($filename);
  55.  
  56. if ($totalSize > $limit) {
  57. logInfo("Deleting {$filename}");
  58. unlink($filename);
  59. }
  60. }
  61. }
  62.  
  63. /**
  64. * Entry point.
  65. */
  66. function main() {
  67. global $logs;
  68.  
  69. foreach ($logs as $folder) {
  70. echo "Processing {$folder['path']}\n";
  71. processFolder($folder['path'], $folder['prefix'], $folder['limit']);
  72. }
  73. }
  74.  
  75. // Get started
  76. main();
Add Comment
Please, Sign In to add comment