1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
| <?php class ErrorMonitor { private array $errorStats = []; private array $errorLog = []; private int $maxLogSize = 1000; public function __construct() { set_error_handler([$this, 'handleError']); set_exception_handler([$this, 'handleException']); register_shutdown_function([$this, 'handleShutdown']); } public function handleError(int $severity, string $message, string $file, int $line): bool { $errorType = $this->getErrorTypeName($severity); $errorInfo = [ 'type' => 'ERROR', 'severity' => $severity, 'severity_name' => $errorType, 'message' => $message, 'file' => $file, 'line' => $line, 'timestamp' => time(), 'memory_usage' => memory_get_usage(true), 'trace' => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) ]; $this->logError($errorInfo); $this->updateStats($errorType); if ($severity & (E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR)) { throw new ErrorException($message, 0, $severity, $file, $line); } return true; } public function handleException(Throwable $exception): void { $errorInfo = [ 'type' => 'EXCEPTION', 'class' => get_class($exception), 'message' => $exception->getMessage(), 'code' => $exception->getCode(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'timestamp' => time(), 'memory_usage' => memory_get_usage(true), 'trace' => $exception->getTrace() ]; $this->logError($errorInfo); $this->updateStats('EXCEPTION'); $this->displayError($errorInfo); } public function handleShutdown(): void { $lastError = error_get_last(); if ($lastError && in_array($lastError['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR])) { $errorInfo = [ 'type' => 'FATAL_ERROR', 'severity' => $lastError['type'], 'severity_name' => $this->getErrorTypeName($lastError['type']), 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line'], 'timestamp' => time(), 'memory_usage' => memory_get_usage(true) ]; $this->logError($errorInfo); $this->updateStats('FATAL_ERROR'); } } private function getErrorTypeName(int $severity): string { return match($severity) { E_ERROR => 'E_ERROR', E_WARNING => 'E_WARNING', E_PARSE => 'E_PARSE', E_NOTICE => 'E_NOTICE', E_CORE_ERROR => 'E_CORE_ERROR', E_CORE_WARNING => 'E_CORE_WARNING', E_COMPILE_ERROR => 'E_COMPILE_ERROR', E_COMPILE_WARNING => 'E_COMPILE_WARNING', E_USER_ERROR => 'E_USER_ERROR', E_USER_WARNING => 'E_USER_WARNING', E_USER_NOTICE => 'E_USER_NOTICE', E_STRICT => 'E_STRICT', E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', E_DEPRECATED => 'E_DEPRECATED', E_USER_DEPRECATED => 'E_USER_DEPRECATED', default => 'UNKNOWN' }; } private function logError(array $errorInfo): void { $this->errorLog[] = $errorInfo; if (count($this->errorLog) > $this->maxLogSize) { array_shift($this->errorLog); } $logMessage = sprintf( "[%s] %s: %s in %s:%d\n", date('Y-m-d H:i:s', $errorInfo['timestamp']), $errorInfo['severity_name'] ?? $errorInfo['class'] ?? $errorInfo['type'], $errorInfo['message'], $errorInfo['file'], $errorInfo['line'] ); error_log($logMessage, 3, 'error.log'); } private function updateStats(string $errorType): void { if (!isset($this->errorStats[$errorType])) { $this->errorStats[$errorType] = 0; } $this->errorStats[$errorType]++; } private function displayError(array $errorInfo): void { if (php_sapi_name() === 'cli') { echo "\n=== 未捕获的异常 ===\n"; echo "类型: {$errorInfo['class']}\n"; echo "消息: {$errorInfo['message']}\n"; echo "文件: {$errorInfo['file']}:{$errorInfo['line']}\n"; } else { http_response_code(500); echo json_encode([ 'error' => true, 'message' => '服务器内部错误', 'timestamp' => $errorInfo['timestamp'] ]); } } public function getErrorStats(): array { return $this->errorStats; } public function getRecentErrors(int $limit = 10): array { return array_slice($this->errorLog, -$limit); } public function clearErrorLog(): void { $this->errorLog = []; $this->errorStats = []; } public function generateReport(): string { $report = "=== 错误监控报告 ===\n"; $report .= "生成时间: " . date('Y-m-d H:i:s') . "\n"; $report .= "总错误数: " . array_sum($this->errorStats) . "\n\n"; if (!empty($this->errorStats)) { $report .= "错误统计:\n"; foreach ($this->errorStats as $type => $count) { $report .= " $type: $count\n"; } $report .= "\n"; } $recentErrors = $this->getRecentErrors(5); if (!empty($recentErrors)) { $report .= "最近错误:\n"; foreach ($recentErrors as $error) { $report .= sprintf( " [%s] %s: %s\n", date('H:i:s', $error['timestamp']), $error['severity_name'] ?? $error['class'] ?? $error['type'], $error['message'] ); } } return $report; } }
class PerformanceMonitor { private array $timers = []; private array $memorySnapshots = []; public function startTimer(string $name): void { $this->timers[$name] = [ 'start' => hrtime(true), 'start_memory' => memory_get_usage(true) ]; } public function endTimer(string $name): ?array { if (!isset($this->timers[$name])) { return null; } $timer = $this->timers[$name]; $endTime = hrtime(true); $endMemory = memory_get_usage(true); $result = [ 'name' => $name, 'duration_ns' => $endTime - $timer['start'], 'duration_ms' => ($endTime - $timer['start']) / 1e6, 'memory_used' => $endMemory - $timer['start_memory'], 'peak_memory' => memory_get_peak_usage(true) ]; unset($this->timers[$name]); return $result; } public function snapshot(string $name): void { $this->memorySnapshots[$name] = [ 'timestamp' => time(), 'memory_usage' => memory_get_usage(true), 'peak_memory' => memory_get_peak_usage(true) ]; } public function getSnapshots(): array { return $this->memorySnapshots; } }
echo "\n=== 错误监控系统示例 ===\n";
$errorMonitor = new ErrorMonitor(); $performanceMonitor = new PerformanceMonitor();
$performanceMonitor->startTimer('test_operation');
try { $data = []; for ($i = 0; $i < 1000; $i++) { $data[] = $i * 2; if ($i === 500) { trigger_error("这是一个测试警告", E_USER_WARNING); } if ($i === 750) { throw new RuntimeException("这是一个测试异常"); } } } catch (Exception $e) { echo "捕获到异常: " . $e->getMessage() . "\n"; }
$performanceResult = $performanceMonitor->endTimer('test_operation'); $performanceMonitor->snapshot('after_operation');
if ($performanceResult) { echo "\n性能监控结果:\n"; echo "操作耗时: " . round($performanceResult['duration_ms'], 2) . "ms\n"; echo "内存使用: " . number_format($performanceResult['memory_used']) . " bytes\n"; echo "峰值内存: " . number_format($performanceResult['peak_memory']) . " bytes\n"; }
echo "\n" . $errorMonitor->generateReport();
echo "\n=== PHP 8 错误处理总结 ===\n"; echo "主要改进:\n"; echo "1. 更多警告升级为异常,提供一致的错误处理\n"; echo "2. 改进的类型错误消息,更容易调试\n"; echo "3. 更好的堆栈跟踪信息\n"; echo "4. 敏感参数隐藏功能\n"; echo "5. 更强大的错误监控和日志系统\n"; ?>
|