Created
February 27, 2025 02:52
-
-
Save galbaras/cc16438f490b28fb2c5d5e785e9a1515 to your computer and use it in GitHub Desktop.
Trim large log files to a maximum number of days
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /* | |
| * If the log file exceeds $max_size, create a backup copy of theit and trim it to contain only messages from the last $max_days | |
| */ | |
| $max_days = 90; | |
| $max_size = 1048576; // 1 MB | |
| $logfile = ABSPATH . 'error_log'; | |
| if ( ! file_exists( $logfile ) ) { | |
| echo "<p>$logfile does not exist.</p>"; | |
| return; | |
| } | |
| if ( filesize( $logfile ) <= $max_size ) { | |
| echo "<p>$logfile is still small. Skipping.</p>"; | |
| return; | |
| } | |
| $date = ''; | |
| for ( $i = 0; $i < $max_days; $i++ ) { | |
| $date .= date( 'd-M-Y', strtotime( "-$i days" ) ) . '|'; | |
| } | |
| if ( ! empty( $date ) ) { | |
| $date = '^.(' . trim( $date, '|' ) . ')'; | |
| } | |
| $pattern = '/' . $date . '.+' . ( isset( $search ) ? $search : '' ) . '[^\[]*/mi'; | |
| $contents = file_get_contents( $logfile ); | |
| $found = preg_match_all( $pattern, $contents, $matches ); | |
| if ( ! $found ) { | |
| echo "<p>$logfile contains no messages from the past $max_days days. Skipping.</p>"; | |
| return; | |
| } | |
| echo "<p>$logfile contains $found matches. Trimming.</p>"; | |
| if ( copy( $logfile, $logfile . '.bak' ) ) { | |
| echo '<p>Created backup copy.</p>'; | |
| } | |
| $newsize = file_put_contents( $logfile, $matches[0] ); | |
| if ( $newsize === false ) { | |
| echo "<p>Failed to write $logfile.</p>"; | |
| return; | |
| } | |
| $newsize = round( $newsize / 1048576, 2 ); | |
| echo "<p>$logfile trimmed to $newsize MB.</p>"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment