Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env php
- <?php
- /* This script is designed to delete logs files if it exceeds a defined size limit.
- * Size limit is applied to all log files, instead of individual file.
- * The logs are sorted by filename in reversed alphabetical order.
- * Each file's size is counted and sum with previous file. If size limit is exceeded,
- * subsequent files are deleted.
- */
- const MB = 1024 * 1024;
- /** CONFIGURATIONS **/
- /* State your configurations here.
- * - limit: Size in bytes.
- * - path: Absolute path to folder containing log files.
- * - prefix: Log filename prefix.
- */
- $logs = [
- ['limit' => 700 * MB, 'path' => '/path/to/application/logs', 'prefix' => 'log-'],
- ['limit' => 100 * MB, 'path' => '/path/to/another/log', 'prefix' => 'example-'],
- ];
- /** CODE **/
- /**
- * Send message to STDOUT.
- * @param string $message
- */
- function logInfo($message) {
- fwrite(STDOUT, date('Y-m-d H:i:s')." {$message}".PHP_EOL);
- }
- /**
- * Send message to STDERR
- * @param string $message
- */
- function logError($message) {
- fwrite(STDERR, date('Y-m-d H:i:s')." {$message}".PHP_EOL);
- }
- /**
- * Check total file size and delete files.
- * @param string $path Folder path containing log files
- * @param string $prefix Log filename prefix
- * @param int $limit Size limit in bytes
- */
- function processFolder($path, $prefix, $limit) {
- $path = rtrim($path, '/').'/';
- $totalSize = 0;
- // This sorting **assumes** filename contain timestamp
- foreach (array_reverse(glob("{$path}{$prefix}*")) as $filename) {
- $totalSize += filesize($filename);
- if ($totalSize > $limit) {
- logInfo("Deleting {$filename}");
- unlink($filename);
- }
- }
- }
- /**
- * Entry point.
- */
- function main() {
- global $logs;
- foreach ($logs as $folder) {
- echo "Processing {$folder['path']}\n";
- processFolder($folder['path'], $folder['prefix'], $folder['limit']);
- }
- }
- // Get started
- main();
Add Comment
Please, Sign In to add comment