Usage
Core patterns and workflows for WPZylos Logger.
Basic Logging
Log Levels
use WPZylos\Framework\Logger\Logger;
$logger = new Logger($context);
// In order of severity (highest to lowest)
$logger->emergency('System is unusable');
$logger->alert('Action must be taken immediately');
$logger->critical('Critical conditions');
$logger->error('Error conditions');
$logger->warning('Warning conditions');
$logger->notice('Normal but significant condition');
$logger->info('Informational messages');
$logger->debug('Debug-level messages');
With Context
$logger->info('User logged in', [
'user_id' => $user->ID,
'ip' => $_SERVER['REMOTE_ADDR'],
'user_agent' => $_SERVER['HTTP_USER_AGENT'],
]);
$logger->error('Database query failed', [
'query' => $query,
'error' => $wpdb->last_error,
'error_code' => $wpdb->last_error_code,
]);
Message Interpolation
Context values can be interpolated into messages:
$logger->info('User {username} logged in from {ip}', [
'username' => $user->user_login,
'ip' => $_SERVER['REMOTE_ADDR'],
]);
// Output: User john_doe logged in from 192.168.1.1
Log by Level
Debug (Development)
if (WP_DEBUG) {
$logger->debug('Variable state', ['data' => $data]);
}
Info (Normal Operations)
$logger->info('Cron job started', ['job' => 'daily_cleanup']);
$logger->info('Email sent', ['to' => $email, 'subject' => $subject]);
Warning (Potential Issues)
$logger->warning('Deprecated function used', [
'function' => 'old_method',
'file' => __FILE__,
'line' => __LINE__,
]);
Error (Failures)
try {
$this->processPayment($order);
} catch (\Exception $e) {
$logger->error('Payment processing failed', [
'order_id' => $order->id,
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
}
Exception Logging
try {
$this->riskyOperation();
} catch (\Throwable $e) {
// Pass the exception object via the 'exception' key
// The logger will auto-append the stack trace
$logger->error('Operation failed: {message}', [
'message' => $e->getMessage(),
'exception' => $e,
]);
}
Conditional Logging
// Log only in debug mode
if (WP_DEBUG) {
$logger->debug('Debug info', $context);
}
// Log only for specific users
if (current_user_can('manage_options')) {
$logger->info('Admin action', $context);
}