Kotchasan Framework Documentation
Logger Class - Logging System
Logger Class - Logging System
The Logger class provides a simple and flexible logging interface for Kotchasan applications with support for multiple destinations and log levels.
Namespace
Kotchasan\LoggerOverview
The Logger class provides:
- Log to file or system log
- Multiple log levels (debug, info, warning, error)
- Security event logging
- Exception logging with stack trace
- API error logging
- Singleton pattern implementation
Public Methods (10 methods)
create()
Create File Logger instance
public static function create(): \Kotchasan\Logger\LoggerInterfaceReturns: FileLogger instance (singleton)
Example:
$logger = Logger::create();
$logger->info('Application started');system()
Create System Logger instance (logs to Apache/PHP error log)
public static function system(): \Kotchasan\Logger\SystemLoggerReturns: SystemLogger instance (singleton)
Example:
$logger = Logger::system();
$logger->error('Critical system error');logToDestination()
Log to destination(s) based on LOG_DESTINATION constant
public static function logToDestination(
string $level,
string $message,
array $context = []
): voidParameters:
$level- Log level (debug, info, warning, error)$message- Message to log$context- Additional context data (optional)
LOG_DESTINATION values:
LOG_FILE- Log to file onlyLOG_SYSTEM- Log to system log onlyLOG_BOTH- Log to both (default)
Example:
Logger::logToDestination('info', 'User logged in', ['user_id' => 123]);debug()
Log debug message
public static function debug(string $message, array $context = []): voidExample:
Logger::debug('SQL Query executed', [
'query' => 'SELECT * FROM users',
'execution_time' => '0.05s'
]);info()
Log info message
public static function info(string $message, array $context = []): voidExample:
Logger::info('User registration completed', [
'email' => 'user@example.com'
]);warning()
Log warning message
public static function warning(string $message, array $context = []): voidExample:
Logger::warning('Disk space low', [
'free_space' => '10GB',
'threshold' => '20GB'
]);error()
Log error message
public static function error(string $message, array $context = []): voidExample:
Logger::error('Database connection failed', [
'host' => 'localhost',
'error' => 'Connection refused'
]);security()
Log security event (logs to both file and system log)
public static function security(string $event, array $context = []): voidExample:
Logger::security('Failed login attempt', [
'ip' => '192.168.1.100',
'username' => 'admin',
'attempts' => 5
]);exception()
Log exception with full stack trace
public static function exception(
\Throwable $exception,
string $additionalContext = ''
): voidExample:
try {
// some code
} catch (Exception $e) {
Logger::exception($e, 'Error during user registration');
}apiError()
Log API error with HTTP status code
public static function apiError(
int $code,
string $message,
array $context = []
): voidExample:
Logger::apiError(404, 'Resource not found', [
'endpoint' => '/api/users/999'
]);Complete Usage Examples
1. Basic Logging
use Kotchasan\Logger;
// Debug message
Logger::debug('Starting process', ['step' => 1]);
// Info message
Logger::info('Process completed successfully');
// Warning message
Logger::warning('Slow query detected', [
'query' => 'SELECT * FROM large_table',
'time' => '2.5s'
]);
// Error message
Logger::error('Payment failed', [
'order_id' => 'ORD-12345',
'amount' => 1000
]);2. Application Lifecycle Logging
use Kotchasan\Logger;
class Application
{
public function start()
{
Logger::info('Application starting', [
'version' => '1.0.0',
'environment' => 'production'
]);
try {
$this->initialize();
Logger::info('Application initialized successfully');
} catch (\Exception $e) {
Logger::exception($e, 'Failed to initialize application');
Logger::error('Application startup failed');
throw $e;
}
}
private function initialize()
{
Logger::debug('Initializing database connection');
// Initialize database
Logger::debug('Loading configuration');
// Load config
Logger::debug('Registering services');
// Register services
}
}3. Security Event Monitoring
use Kotchasan\Logger;
class SecurityMonitor
{
public function checkLogin($username, $password, $ip)
{
if ($this->isLoginFailed($username, $password)) {
Logger::security('Failed login attempt', [
'username' => $username,
'ip' => $ip,
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
'timestamp' => date('Y-m-d H:i:s')
]);
$attempts = $this->getFailedAttempts($ip);
if ($attempts > 5) {
Logger::security('Suspicious activity detected', [
'ip' => $ip,
'failed_attempts' => $attempts,
'action' => 'IP blocked'
]);
$this->blockIP($ip);
}
}
}
public function detectSQLInjection($input)
{
if ($this->containsSQLKeywords($input)) {
Logger::security('SQL injection attempt', [
'input' => $input,
'ip' => $_SERVER['REMOTE_ADDR'],
'uri' => $_SERVER['REQUEST_URI']
]);
}
}
}4. API Error Handling
use Kotchasan\Logger;
class APIController
{
public function handleRequest($endpoint)
{
try {
$result = $this->processRequest($endpoint);
if (!$result) {
Logger::apiError(404, 'Resource not found', [
'endpoint' => $endpoint,
'method' => $_SERVER['REQUEST_METHOD']
]);
return ['error' => 'Not found', 'code' => 404];
}
Logger::info('API request successful', [
'endpoint' => $endpoint,
'response_time' => $this->getResponseTime()
]);
return $result;
} catch (\Exception $e) {
Logger::apiError(500, 'Internal server error', [
'endpoint' => $endpoint,
'error' => $e->getMessage()
]);
Logger::exception($e);
return ['error' => 'Server error', 'code' => 500];
}
}
}5. Exception Handling with Context
use Kotchasan\Logger;
class PaymentProcessor
{
public function processPayment($orderId, $amount)
{
Logger::info('Processing payment', [
'order_id' => $orderId,
'amount' => $amount
]);
try {
$this->validatePayment($orderId, $amount);
$result = $this->chargeCard($amount);
if ($result['success']) {
Logger::info('Payment successful', [
'order_id' => $orderId,
'transaction_id' => $result['transaction_id']
]);
} else {
Logger::warning('Payment declined', [
'order_id' => $orderId,
'reason' => $result['reason']
]);
}
return $result;
} catch (\InvalidArgumentException $e) {
Logger::warning('Invalid payment parameters', [
'order_id' => $orderId,
'error' => $e->getMessage()
]);
throw $e;
} catch (\Exception $e) {
Logger::exception($e, "Payment processing failed for order {$orderId}");
throw $e;
}
}
}6. Custom Log Destinations
use Kotchasan\Logger;
// Log to file only
define('LOG_DESTINATION', 'LOG_FILE');
Logger::logToDestination('info', 'File only log');
// Log to system log only
define('LOG_DESTINATION', 'LOG_SYSTEM');
Logger::logToDestination('error', 'System only log');
// Log to both
define('LOG_DESTINATION', 'LOG_BOTH');
Logger::logToDestination('warning', 'Both destinations', [
'data' => 'important'
]);7. Performance Monitoring
use Kotchasan\Logger;
class PerformanceMonitor
{
private $startTime;
public function start($operation)
{
$this->startTime = microtime(true);
Logger::debug("Starting: {$operation}");
}
public function end($operation)
{
$duration = microtime(true) - $this->startTime;
if ($duration > 1.0) {
Logger::warning("Slow operation detected", [
'operation' => $operation,
'duration' => round($duration, 3).'s'
]);
} else {
Logger::debug("Completed: {$operation}", [
'duration' => round($duration, 3).'s'
]);
}
}
}
// Usage
$monitor = new PerformanceMonitor();
$monitor->start('Database query');
// ... execute query ...
$monitor->end('Database query');Best Practices
1. Use Appropriate Log Levels
// ✅ Good: Use correct level
Logger::debug('Detailed debugging info'); // Development only
Logger::info('Normal operation'); // Information
Logger::warning('Something unexpected'); // Needs attention
Logger::error('Something failed'); // Needs immediate action
// ❌ Bad: Wrong level
Logger::error('User clicked button'); // Wrong - should be info
Logger::debug('Database connection failed'); // Wrong - should be error2. Provide Useful Context
// ✅ Good: Meaningful context
Logger::error('Payment failed', [
'order_id' => $orderId,
'amount' => $amount,
'error_code' => $errorCode,
'timestamp' => time()
]);
// ❌ Bad: Insufficient context
Logger::error('Payment failed'); // Lacks details3. Log Security Events
// ✅ Good: Log important security events
Logger::security('Failed login', ['ip' => $ip, 'username' => $user]);
Logger::security('Unauthorized access', ['resource' => $resource]);
// ⚠️ Warning: Don't log sensitive data
Logger::security('Password changed', [
'user_id' => $userId
// ❌ Don't log actual passwords!
]);4. Handle Exceptions Properly
// ✅ Good: Log with context
try {
$this->dangerousOperation();
} catch (Exception $e) {
Logger::exception($e, 'Context: performing user operation');
// handle exception
}
// ✅ Good: Log before rethrowing
catch (Exception $e) {
Logger::exception($e);
throw $e; // Rethrow if needed
}5. Optimize Performance
// ✅ Good: Avoid expensive operations in production
if (defined('DEBUG') && DEBUG > 0) {
Logger::debug('Complex data', [
'data' => $this->expensiveSerialize()
]);
}
// ❌ Bad: Expensive operations always run
Logger::debug('Data', [
'data' => $this->expensiveSerialize() // Runs always!
]);Summary
The Logger class is essential for:
- ✅ Application event logging
- ✅ Error and exception tracking
- ✅ Security monitoring
- ✅ Application debugging
- 📁 Multiple destinations (file/system)
- 🔍 Rich context data
Suitable for:
- Application monitoring
- Error tracking
- Security auditing
- Performance analysis
- Debugging
File Size: 194 lines
Public Methods: 10 methods
Pattern: Facade + Singleton