Kotchasan Framework Documentation
Logger Class - ระบบบันทึกข้อมูล
Logger Class - ระบบบันทึกข้อมูล
คลาส Logger เป็นคลาสสำหรับบันทึกข้อมูล (Logging) ในรูปแบบต่างๆ รองรับการบันทึกไปยังไฟล์หรือ system log
Namespace
Kotchasan\Loggerภาพรวม
คลาส Logger ให้บริการ:
- บันทึก log ไปยัง file หรือ system log
- รองรับ log levels หลายระดับ (debug, info, warning, error)
- บันทึก security events
- บันทึก exceptions พร้อม stack trace
- บันทึก API errors
- ใช้ Singleton pattern
Public Methods (10 methods)
create()
สร้าง File Logger instance
public static function create(): \Kotchasan\Logger\LoggerInterfaceคืนค่า: FileLogger instance (singleton)
ตัวอย่าง:
$logger = Logger::create();
$logger->info('Application started');system()
สร้าง System Logger instance (บันทึกไปยัง Apache/PHP error log)
public static function system(): \Kotchasan\Logger\SystemLoggerคืนค่า: SystemLogger instance (singleton)
ตัวอย่าง:
$logger = Logger::system();
$logger->error('Critical system error');logToDestination()
บันทึก log ไปยังปลายทางที่กำหนดใน LOG_DESTINATION
public static function logToDestination(
string $level,
string $message,
array $context = []
): voidพารามิเตอร์:
$level- ระดับ log (debug, info, warning, error)$message- ข้อความที่ต้องการบันทึก$context- ข้อมูลเพิ่มเติม (optional)
LOG_DESTINATION values:
LOG_FILE- บันทึกเฉพาะไฟล์LOG_SYSTEM- บันทึกเฉพาะ system logLOG_BOTH- บันทึกทั้งสอง (default)
ตัวอย่าง:
Logger::logToDestination('info', 'User logged in', ['user_id' => 123]);debug()
บันทึก debug message
public static function debug(string $message, array $context = []): voidตัวอย่าง:
Logger::debug('SQL Query executed', [
'query' => 'SELECT * FROM users',
'execution_time' => '0.05s'
]);info()
บันทึก info message
public static function info(string $message, array $context = []): voidตัวอย่าง:
Logger::info('User registration completed', [
'email' => 'user@example.com'
]);warning()
บันทึก warning message
public static function warning(string $message, array $context = []): voidตัวอย่าง:
Logger::warning('Disk space low', [
'free_space' => '10GB',
'threshold' => '20GB'
]);error()
บันทึก error message
public static function error(string $message, array $context = []): voidตัวอย่าง:
Logger::error('Database connection failed', [
'host' => 'localhost',
'error' => 'Connection refused'
]);security()
บันทึก security event (บันทึกทั้ง file และ system log)
public static function security(string $event, array $context = []): voidตัวอย่าง:
Logger::security('Failed login attempt', [
'ip' => '192.168.1.100',
'username' => 'admin',
'attempts' => 5
]);exception()
บันทึก exception พร้อม stack trace
public static function exception(
\Throwable $exception,
string $additionalContext = ''
): voidตัวอย่าง:
try {
// some code
} catch (Exception $e) {
Logger::exception($e, 'Error during user registration');
}apiError()
บันทึก API error พร้อม HTTP status code
public static function apiError(
int $code,
string $message,
array $context = []
): voidตัวอย่าง:
Logger::apiError(404, 'Resource not found', [
'endpoint' => '/api/users/999'
]);ตัวอย่างการใช้งานแบบสมบูรณ์
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 Startup 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 Logger
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 Handler
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 Logging with Destinations
use Kotchasan\Logger;
// บันทึกเฉพาะไฟล์
define('LOG_DESTINATION', 'LOG_FILE');
Logger::logToDestination('info', 'File only log');
// บันทึกเฉพาะ system log
define('LOG_DESTINATION', 'LOG_SYSTEM');
Logger::logToDestination('error', 'System only log');
// บันทึกทั้งสอง
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'
]);
}
}
}
// ใช้งาน
$monitor = new PerformanceMonitor();
$monitor->start('Database query');
// ... execute query ...
$monitor->end('Database query');Best Practices
1. Log Levels
// ✅ ใช้ 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
// ❌ อย่าใช้ผิด level
Logger::error('User clicked button'); // ผิด - ควรใช้ info
Logger::debug('Database connection failed'); // ผิด - ควรใช้ error2. Context Data
// ✅ ให้ context ที่มีประโยชน์
Logger::error('Payment failed', [
'order_id' => $orderId,
'amount' => $amount,
'error_code' => $errorCode,
'timestamp' => time()
]);
// ❌ Context ไม่เพียงพอ
Logger::error('Payment failed'); // ขาดรายละเอียด3. Security Events
// ✅ บันทึก security events ที่สำคัญ
Logger::security('Failed login', ['ip' => $ip, 'username' => $user]);
Logger::security('Unauthorized access', ['resource' => $resource]);
// ⚠️ ระวัง sensitive data
Logger::security('Password changed', [
'user_id' => $userId
// ❌ อย่าบันทึก password จริง!
]);4. Exceptions
// ✅ บันทึก exception พร้อม context
try {
$this->dangerousOperation();
} catch (Exception $e) {
Logger::exception($e, 'Context: performing user operation');
// handle exception
}
// ✅ บันทึกก่อน rethrow
catch (Exception $e) {
Logger::exception($e);
throw $e; // จำเป็นต้อง throw ต่อ
}5. Performance
// ✅ หลีกเลี่ยง expensive operations ใน debug
if (defined('DEBUG') && DEBUG > 0) {
Logger::debug('Complex data', [
'data' => $this->expensiveSerialize()
]);
}
// ❌ อย่าทำ expensive operations เสมอ
Logger::debug('Data', [
'data' => $this->expensiveSerialize() // ทำทุกครั้ง!
]);สรุป
คลาส Logger เป็นเครื่องมือสำคัญสำหรับ:
- ✅ บันทึก application events
- ✅ ติดตาม errors และ exceptions
- ✅ Monitor security
- ✅ Debug applications
- 📁 รองรับหลายปลายทาง (file/system)
- 🔍 มี context data
เหมาะสำหรับ:
- Application monitoring
- Error tracking
- Security auditing
- Performance analysis
- Debugging
ไฟล์ขนาด: 194 บรรทัด
Public Methods: 10 methods
Pattern: Facade + Singleton