Skip to main content

Monitoring

Performance Metrics Collection

php

<?php
class PerformanceMonitor
{
private float $startTime;
private int $startMemory;
private array $metrics = [];
public function __construct()
{
$this->startTime = microtime(true);
$this->startMemory = memory_get_usage(true);
}
public function recordMetric(string $name, mixed $value): void
{
$this->metrics[$name] = [
'value' => $value,
'timestamp' => microtime(true),
'memory' => memory_get_usage(true)
];
}
public function getExecutionTime(): float
{
return microtime(true) - $this->startTime;
}
public function getMemoryUsage(): array
{
return [
'current' => memory_get_usage(true),
'peak' => memory_get_peak_usage(true),
'initial' => $this->startMemory
];
}
public function exportMetrics(): array
{
return [
'execution_time' => $this->getExecutionTime(),
'memory_usage' => $this->getMemoryUsage(),
'custom_metrics' => $this->metrics,
'system_info' => [
'php_version' => PHP_VERSION,
'server_time' => date('Y-m-d H:i:s'),
'load_average' => sys_getloadavg()
]
];
}
}

Health Check Endpoint

php

<?php
class HealthCheckController
{
private array $checks = [];
public function __construct()
{
$this->checks = [
'database' => [$this, 'checkDatabase'],
'redis' => [$this, 'checkRedis'],
'filesystem' => [$this, 'checkFilesystem'],
'memory' => [$this, 'checkMemory']
];
}
public function health(): array
{
$results = [];
$overallStatus = 'healthy';
foreach ($this->checks as $name => $check) {
try {
$result = call_user_func($check);
$results[$name] = $result;
if ($result['status'] !== 'OK') {
$overallStatus = 'unhealthy';
}
} catch (Exception $e) {
$results[$name] = [
'status' => 'ERROR',
'message' => $e->getMessage()
];
$overallStatus = 'unhealthy';
}
}
return [
'status' => $overallStatus,
'timestamp' => date('c'),
'checks' => $results
];
}
private function checkDatabase(): array
{
$pdo = DatabaseConnection::getInstance();
$stmt = $pdo->query('SELECT 1');
return [
'status' => 'OK',
'response_time' => '< 1ms'
];
}
private function checkRedis(): array
{
$redis = RedisConnection::getInstance();
$redis->ping();
return [
'status' => 'OK',
'response_time' => '< 1ms'
];
}
private function checkFilesystem(): array
{
$tempFile = tempnam(sys_get_temp_dir(), 'health_check');
file_put_contents($tempFile, 'test');
$content = file_get_contents($tempFile);
unlink($tempFile);
return [
'status' => $content === 'test' ? 'OK' : 'ERROR',
'writable' => is_writable(sys_get_temp_dir())
];
}
private function checkMemory(): array
{
$usage = memory_get_usage(true);
$limit = ini_get('memory_limit');
$limitBytes = $this->convertToBytes($limit);
$percentage = ($usage / $limitBytes) * 100;
return [
'status' => $percentage < 80 ? 'OK' : 'WARNING',
'usage_mb' => round($usage / 1024 / 1024, 2),
'limit' => $limit,
'percentage' => round($percentage, 2)
];
}
private function convertToBytes(string $value): int
{
$unit = strtolower(substr($value, -1));
$value = (int) $value;
switch ($unit) {
case 'g': return $value * 1024 * 1024 * 1024;
case 'm': return $value * 1024 * 1024;
case 'k': return $value * 1024;
default: return $value;
}
}
}

Logging System

php

<?php
class Logger
{
private string $logPath;
private string $level;
private const LEVELS = [
'DEBUG' => 0,
'INFO' => 1,
'WARNING' => 2,
'ERROR' => 3,
'CRITICAL' => 4
];
public function __construct(string $logPath = '/var/log/app.log', string $level = 'INFO')
{
$this->logPath = $logPath;
$this->level = $level;
}
public function log(string $level, string $message, array $context = []): void
{
if (self::LEVELS[$level] < self::LEVELS[$this->level]) {
return;
}
$timestamp = date('Y-m-d H:i:s');
$contextStr = !empty($context) ? ' ' . json_encode($context) : '';
$logLine = "[{$timestamp}] {$level}: {$message}{$contextStr}" . PHP_EOL;
file_put_contents($this->logPath, $logLine, FILE_APPEND | LOCK_EX);
}
public function debug(string $message, array $context = []): void
{
$this->log('DEBUG', $message, $context);
}
public function info(string $message, array $context = []): void
{
$this->log('INFO', $message, $context);
}
public function warning(string $message, array $context = []): void
{
$this->log('WARNING', $message, $context);
}
public function error(string $message, array $context = []): void
{
$this->log('ERROR', $message, $context);
}
}