Automattic\WooCommerce\Internal\Admin\Logging
LogHandlerFileV2::delete_logs_before_timestamp
Delete all logs older than a specified timestamp.
Method of the class: LogHandlerFileV2{}
Hooks from the method
Returns
Int. The number of files that were deleted.
Usage
$LogHandlerFileV2 = new LogHandlerFileV2(); $LogHandlerFileV2->delete_logs_before_timestamp( $timestamp ): int;
- $timestamp(int)
- All files created before this timestamp will be deleted.
LogHandlerFileV2::delete_logs_before_timestamp() LogHandlerFileV2::delete logs before timestamp code WC 11.0.1
public function delete_logs_before_timestamp( int $timestamp = 0 ): int {
if ( ! $timestamp ) {
return 0;
}
$deleted = 0;
$skipped = 0;
// Fetch and delete in batches so that sites with more than the default
// per-page of log files don't leave expired files behind.
do {
$files = $this->file_controller->get_files(
array(
'date_filter' => 'created',
'date_start' => 1,
'date_end' => $timestamp,
'per_page' => self::DELETE_BATCH_SIZE,
'offset' => $skipped,
)
);
if ( is_wp_error( $files ) || ! is_array( $files ) ) {
break;
}
$fetched_count = count( $files );
$files = array_filter(
$files,
function ( $file ) use ( $timestamp ) {
/**
* Allows preventing an expired log file from being deleted.
*
* @param bool $delete True to delete the file.
* @param File $file The log file object.
* @param int $timestamp The expiration threshold.
*
* @since 8.7.0
*/
$delete = apply_filters( 'woocommerce_logger_delete_expired_file', true, $file, $timestamp );
return boolval( $delete );
}
);
$file_count = count( $files );
$vetoed_count = $fetched_count - $file_count;
$deleted_in_batch = 0;
if ( $file_count > 0 ) {
$file_ids = array_map(
fn( $file ) => $file->get_file_id(),
$files
);
$deleted_in_batch = $this->file_controller->delete_files( $file_ids );
$deleted += $deleted_in_batch;
}
// Deleted files disappear from the directory, so only vetoed files
// need to be skipped. If no progress was made, skip the full page to
// avoid retrying a permanently vetoed or undeletable batch forever.
$skipped += $deleted_in_batch > 0 ? $vetoed_count : $fetched_count;
} while ( self::DELETE_BATCH_SIZE === $fetched_count );
if ( $deleted > 0 ) {
$this->handle(
time(),
'info',
sprintf(
esc_html(
// translators: %s is a number of log files.
_n(
'%s expired log file was deleted.',
'%s expired log files were deleted.',
$deleted,
'woocommerce'
)
),
number_format_i18n( $deleted )
),
array(
'source' => 'wc_logger',
)
);
}
return $deleted;
}