Automattic\WooCommerce\Internal\Admin\Logging
LogHandlerFileV2::clear
Delete all logs from a specific source.
Method of the class: LogHandlerFileV2{}
No Hooks.
Returns
int. The number of files that were deleted.
Usage
$LogHandlerFileV2 = new LogHandlerFileV2(); $LogHandlerFileV2->clear( $source, $quiet ): int;
- $source(string) (required)
- The source of the log entries.
- $quiet(true|false)
- Whether to suppress the deletion message.
Default:false
LogHandlerFileV2::clear() LogHandlerFileV2::clear code WC 11.1.2
public function clear( string $source, bool $quiet = false ): int {
$source = File::sanitize_source( $source );
// Bail on an empty source: an empty value would match every file and,
// combined with the batched deletion below, wipe out all log files.
if ( '' === $source ) {
return 0;
}
$deleted = 0;
$skipped = 0;
/*
* Fetch and delete in batches so that sources with more than the default
* per-page of log files don't leave files behind.
*
* Order by 'created' rather than the default 'modified'. Because paging
* advances $skipped past undeletable files, the offset is only reliable if
* get_files() returns a stable, strict total order across iterations. For a
* single source, created timestamps (plus rotation) are unique per file,
* whereas modified times can tie -- and on PHP < 8.0 usort() is not stable,
* so tied files could re-order between iterations and strand a deletable file.
*/
do {
$files = $this->file_controller->get_files(
array(
'source' => $source,
'exact_source' => true,
'orderby' => 'created',
'per_page' => self::DELETE_BATCH_SIZE,
'offset' => $skipped,
)
);
if ( is_wp_error( $files ) || ! is_array( $files ) ) {
break;
}
$fetched_count = count( $files );
if ( $fetched_count < 1 ) {
break;
}
$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 files that could
// not be deleted need to be skipped. This avoids retrying a permanently
// undeletable batch forever.
$skipped += $fetched_count - $deleted_in_batch;
} while ( self::DELETE_BATCH_SIZE === $fetched_count );
if ( $deleted > 0 && ! $quiet ) {
$this->handle(
time(),
'info',
sprintf(
esc_html(
// translators: %1$s is a number of log files, %2$s is a slug-style name for a file.
_n(
'%1$s log file from source %2$s was deleted.',
'%1$s log files from source %2$s were deleted.',
$deleted,
'woocommerce'
)
),
number_format_i18n( $deleted ),
sprintf(
'<code>%s</code>',
esc_html( $source )
)
),
array(
'source' => 'wc_logger',
'backtrace' => true,
)
);
}
return $deleted;
}