Files
WP-Site-Sync/includes/class-logger.php
2025-12-14 17:17:16 -06:00

71 lines
1.7 KiB
PHP

<?php
namespace SiteSync;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Logger class for SiteSync plugin.
*
* Handles logging of messages with different levels and context.
*/
class Logger {
public const OPTION_KEY = 'site_sync_logs';
private const MAX = 200;
/**
* Logs a message with a given level and context.
*
* @param string $level The log level (e.g., 'info', 'error').
* @param string $message The log message.
* @param array $context Additional context for the log entry.
*
* @return void
*/
public static function log( string $level, string $message, array $context = array() ): void {
$entry = array(
'ts' => current_time( 'mysql' ),
'level' => strtoupper( $level ),
'message' => $message,
'context' => $context,
);
$logs = get_option( self::OPTION_KEY, array() );
if ( ! is_array( $logs ) ) {
$logs = array();
}
array_unshift( $logs, $entry );
$logs = array_slice( $logs, 0, self::MAX );
update_option( self::OPTION_KEY, $logs );
}
/**
* Retrieves the most recent log entries.
*
* @param int $limit The maximum number of log entries to retrieve.
*
* @return array The array of recent log entries.
*/
public static function recent( int $limit = 50 ): array {
$logs = get_option( self::OPTION_KEY, array() );
if ( ! is_array( $logs ) ) {
return array();
}
return array_slice( $logs, 0, $limit );
}
/**
* Clears all stored log entries.
*
* @return void
*/
public static function clear(): void {
delete_option( self::OPTION_KEY );
}
}