Skip to content

Instantly share code, notes, and snippets.

@hongster
Created August 21, 2018 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hongster/7bbefab7a6e947889429dcd81b59dde8 to your computer and use it in GitHub Desktop.
Save hongster/7bbefab7a6e947889429dcd81b59dde8 to your computer and use it in GitHub Desktop.
Delete log files so that total size of all log files is kept within certain size limit.
#!/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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment