Skip to content

Instantly share code, notes, and snippets.

@YOUR1
Created September 10, 2020 07:38
Show Gist options
  • Save YOUR1/f90e8993a41f6223cb26ffa6565c5a46 to your computer and use it in GitHub Desktop.
Save YOUR1/f90e8993a41f6223cb26ffa6565c5a46 to your computer and use it in GitHub Desktop.
#!/usr/bin/php
<?php
$today = new DateTime();
$firstEntry = new DateTime();
// Set from timestamp (this should be the first log entry of nagios.log.old)
$firstEntry->setTimestamp( 1555408368 );
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod( $firstEntry, $interval, $today );
$lines = largeFileToDateArray('./nagios.log.old');
foreach( $period as $end ){
$linesToWrite = [];
$fileToWrite = "./archives/nagios-" . $end->format("m-d-Y") . "-00.log";
foreach( $lines as $timestamp => $text ) {
$lineTimestamp = new DateTime();
$lineTimestamp->setTimestamp( (int) $timestamp );
if ( $lineTimestamp->format("m-d-Y") == $end->format("m-d-Y") ) {
$linesToWrite[] = "[$timestamp] $text";
}
}
file_put_contents( $fileToWrite, implode(PHP_EOL, $linesToWrite) );
}
function largeFileToDateArray( $fileName ) {
$handle = fopen( $fileName, "r") or die ("Error opening {$fileName}");
$result = [];
if ( $handle ) {
while( !feof( $handle ) ) {
preg_match('/\[(\d+)\] (.*)/', fgets( $handle ), $groups );
@$result[ $groups[1] ] = $groups[2];
}
fclose( $handle );
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment