PHP调试与性能分析工具实战PHP开发中常用的工具有Xdebug用于调试Blackfire或Tideways用于性能分析。今天说说这些工具的使用方法和实战经验。Xdebug是最流行的PHP调试工具。它提供了步进调试、堆栈跟踪、代码覆盖率等功能。php// Xdebug配置 (php.ini)// zend_extensionxdebug// xdebug.modedebug,profile,trace// xdebug.start_with_requestyes// xdebug.client_host127.0.0.1// xdebug.client_port9003// xdebug.idekeyPHPSTORM// xdebug.max_nesting_level256// var_dump增强$data [name 张三,age 28,hobbies [读书, 游泳, 编程],address [city 北京, district 海淀],];var_dump($data);?性能分析是识别瓶颈的关键。Xdebug的profile功能可以生成性能分析文件。php// 待分析代码function processLargeArray(int $size): array{$result [];for ($i 0; $i $size; $i) {$result[] [id $i,name Item $i,value sqrt($i) * sin($i),tags [tag . ($i % 10), category . ($i % 5)],];}return $result;}function filterAndSort(array $items, float $threshold): array{$filtered array_filter($items, fn($item) $item[value] $threshold);usort($filtered, fn($a, $b) $b[value] $a[value]);return array_slice($filtered, 0, 100);}$data processLargeArray(5000);$result filterAndSort($data, 0.5);echo 处理完成结果数: . count($result) . \n;?手动性能测量是快速定位问题的方法phpclass Benchmark{private array $timers [];private array $results [];public function start(string $name): void{$this-timers[$name] [start microtime(true),memory memory_get_usage(true),];}public function stop(string $name): void{if (!isset($this-timers[$name])) return;$timer $this-timers[$name];$this-results[$name] [time (microtime(true) - $timer[start]) * 1000,memory (memory_get_usage(true) - $timer[memory]) / 1024,peak_memory memory_get_peak_usage(true) / 1024 / 1024,];unset($this-timers[$name]);}public function report(): void{echo \n 性能报告 \n;echo str_pad(操作, 30) . str_pad(耗时(ms), 15) . str_pad(内存(KB), 15) . 峰值(MB)\n;echo str_repeat(-, 70) . \n;foreach ($this-results as $name $result) {echo str_pad($name, 30). str_pad(round($result[time], 2), 15). str_pad(round($result[memory], 2), 15). round($result[peak_memory], 2) . \n;}echo str_repeat(-, 70) . \n;}public function reset(): void{$this-timers [];$this-results [];}}$bench new Benchmark();$bench-start(数组生成);$data [];for ($i 0; $i 100000; $i) {$data[] $i;}$bench-stop(数组生成);$bench-start(数组排序);sort($data);$bench-stop(数组排序);$bench-start(数组过滤);$filtered array_filter($data, fn($v) $v % 2 0);$bench-stop(数组过滤);$bench-start(array_map);$mapped array_map(fn($v) $v * 2, $filtered);$bench-stop(array_map);$bench-report();?错误日志和分析是排查线上问题的常用手段phpclass ErrorLogger{private string $logDir;private string $appEnv;public function __construct(string $logDir /var/log/php){$this-logDir $logDir;$this-appEnv $_SERVER[APP_ENV] ?? production;if (!is_dir($logDir)) {mkdir($logDir, 0755, true);}}public function logError(Throwable $e, array $context []): void{$entry [time date(Y-m-d H:i:s),env $this-appEnv,type get_class($e),message $e-getMessage(),file $e-getFile(),line $e-getLine(),trace $e-getTraceAsString(),context $context,request_uri $_SERVER[REQUEST_URI] ?? ,request_method $_SERVER[REQUEST_METHOD] ?? ,];$logFile $this-logDir . /error- . date(Y-m-d) . .log;file_put_contents($logFile,json_encode($entry, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . \n,FILE_APPEND | LOCK_EX);// 严重错误发送告警if ($e instanceof Error || strpos(get_class($e), Fatal) ! false) {$this-sendAlert($entry);}}public function logSlowQuery(string $sql, float $duration, array $bindings []): void{$threshold 1.0;if ($duration $threshold) return;$entry [time date(Y-m-d H:i:s),sql $sql,duration round($duration, 4),bindings $bindings,];$logFile $this-logDir . /slow-query- . date(Y-m-d) . .log;file_put_contents($logFile,json_encode($entry, JSON_UNESCAPED_UNICODE) . \n,FILE_APPEND | LOCK_EX);}private function sendAlert(array $entry): void{if ($this-appEnv production) {// 发送告警邮件或调用告警APIerror_log(严重错误: {$entry[message]});}}}// 全局异常处理器$errorLogger new ErrorLogger();set_exception_handler(function (Throwable $e) use ($errorLogger) {$errorLogger-logError($e);http_response_code(500);if ($_SERVER[APP_ENV] development) {echo 错误;echo {$e-getMessage()};echo {$e-getTraceAsString()};} else {echo 服务器内部错误请稍后重试;}});?慢查询日志是数据库性能分析的重要工具在排查数据库性能问题时非常关键。phpclass SlowQueryLogger{private float $threshold 1.0;private array $queries [];public function __construct(float $threshold 1.0){$this-threshold $threshold;}public function startQuery(string $sql, array $params []): void{$this-queries[] [sql $sql,params $params,start microtime(true),];}public function endQuery(): void{$query array_pop($this-queries);if ($query null) return;$duration (microtime(true) - $query[start]);if ($duration $this-threshold) {$log sprintf([%s] 慢查询 %.4fs: %s\n,date(Y-m-d H:i:s),$duration,$query[sql]);file_put_contents(/tmp/slow-queries.log, $log, FILE_APPEND);}}public function clear(): void{$this-queries [];}}?调试和性能分析是开发的重要环节。Xdebug IDE的步进调试适合定位逻辑错误性能分析工具适合识别性能瓶颈日志分析适合排查线上问题。把这几样工具用好开发和运维效率都会提升不少。
PHP调试与性能分析工具实战
PHP调试与性能分析工具实战PHP开发中常用的工具有Xdebug用于调试Blackfire或Tideways用于性能分析。今天说说这些工具的使用方法和实战经验。Xdebug是最流行的PHP调试工具。它提供了步进调试、堆栈跟踪、代码覆盖率等功能。php// Xdebug配置 (php.ini)// zend_extensionxdebug// xdebug.modedebug,profile,trace// xdebug.start_with_requestyes// xdebug.client_host127.0.0.1// xdebug.client_port9003// xdebug.idekeyPHPSTORM// xdebug.max_nesting_level256// var_dump增强$data [name 张三,age 28,hobbies [读书, 游泳, 编程],address [city 北京, district 海淀],];var_dump($data);?性能分析是识别瓶颈的关键。Xdebug的profile功能可以生成性能分析文件。php// 待分析代码function processLargeArray(int $size): array{$result [];for ($i 0; $i $size; $i) {$result[] [id $i,name Item $i,value sqrt($i) * sin($i),tags [tag . ($i % 10), category . ($i % 5)],];}return $result;}function filterAndSort(array $items, float $threshold): array{$filtered array_filter($items, fn($item) $item[value] $threshold);usort($filtered, fn($a, $b) $b[value] $a[value]);return array_slice($filtered, 0, 100);}$data processLargeArray(5000);$result filterAndSort($data, 0.5);echo 处理完成结果数: . count($result) . \n;?手动性能测量是快速定位问题的方法phpclass Benchmark{private array $timers [];private array $results [];public function start(string $name): void{$this-timers[$name] [start microtime(true),memory memory_get_usage(true),];}public function stop(string $name): void{if (!isset($this-timers[$name])) return;$timer $this-timers[$name];$this-results[$name] [time (microtime(true) - $timer[start]) * 1000,memory (memory_get_usage(true) - $timer[memory]) / 1024,peak_memory memory_get_peak_usage(true) / 1024 / 1024,];unset($this-timers[$name]);}public function report(): void{echo \n 性能报告 \n;echo str_pad(操作, 30) . str_pad(耗时(ms), 15) . str_pad(内存(KB), 15) . 峰值(MB)\n;echo str_repeat(-, 70) . \n;foreach ($this-results as $name $result) {echo str_pad($name, 30). str_pad(round($result[time], 2), 15). str_pad(round($result[memory], 2), 15). round($result[peak_memory], 2) . \n;}echo str_repeat(-, 70) . \n;}public function reset(): void{$this-timers [];$this-results [];}}$bench new Benchmark();$bench-start(数组生成);$data [];for ($i 0; $i 100000; $i) {$data[] $i;}$bench-stop(数组生成);$bench-start(数组排序);sort($data);$bench-stop(数组排序);$bench-start(数组过滤);$filtered array_filter($data, fn($v) $v % 2 0);$bench-stop(数组过滤);$bench-start(array_map);$mapped array_map(fn($v) $v * 2, $filtered);$bench-stop(array_map);$bench-report();?错误日志和分析是排查线上问题的常用手段phpclass ErrorLogger{private string $logDir;private string $appEnv;public function __construct(string $logDir /var/log/php){$this-logDir $logDir;$this-appEnv $_SERVER[APP_ENV] ?? production;if (!is_dir($logDir)) {mkdir($logDir, 0755, true);}}public function logError(Throwable $e, array $context []): void{$entry [time date(Y-m-d H:i:s),env $this-appEnv,type get_class($e),message $e-getMessage(),file $e-getFile(),line $e-getLine(),trace $e-getTraceAsString(),context $context,request_uri $_SERVER[REQUEST_URI] ?? ,request_method $_SERVER[REQUEST_METHOD] ?? ,];$logFile $this-logDir . /error- . date(Y-m-d) . .log;file_put_contents($logFile,json_encode($entry, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . \n,FILE_APPEND | LOCK_EX);// 严重错误发送告警if ($e instanceof Error || strpos(get_class($e), Fatal) ! false) {$this-sendAlert($entry);}}public function logSlowQuery(string $sql, float $duration, array $bindings []): void{$threshold 1.0;if ($duration $threshold) return;$entry [time date(Y-m-d H:i:s),sql $sql,duration round($duration, 4),bindings $bindings,];$logFile $this-logDir . /slow-query- . date(Y-m-d) . .log;file_put_contents($logFile,json_encode($entry, JSON_UNESCAPED_UNICODE) . \n,FILE_APPEND | LOCK_EX);}private function sendAlert(array $entry): void{if ($this-appEnv production) {// 发送告警邮件或调用告警APIerror_log(严重错误: {$entry[message]});}}}// 全局异常处理器$errorLogger new ErrorLogger();set_exception_handler(function (Throwable $e) use ($errorLogger) {$errorLogger-logError($e);http_response_code(500);if ($_SERVER[APP_ENV] development) {echo 错误;echo {$e-getMessage()};echo {$e-getTraceAsString()};} else {echo 服务器内部错误请稍后重试;}});?慢查询日志是数据库性能分析的重要工具在排查数据库性能问题时非常关键。phpclass SlowQueryLogger{private float $threshold 1.0;private array $queries [];public function __construct(float $threshold 1.0){$this-threshold $threshold;}public function startQuery(string $sql, array $params []): void{$this-queries[] [sql $sql,params $params,start microtime(true),];}public function endQuery(): void{$query array_pop($this-queries);if ($query null) return;$duration (microtime(true) - $query[start]);if ($duration $this-threshold) {$log sprintf([%s] 慢查询 %.4fs: %s\n,date(Y-m-d H:i:s),$duration,$query[sql]);file_put_contents(/tmp/slow-queries.log, $log, FILE_APPEND);}}public function clear(): void{$this-queries [];}}?调试和性能分析是开发的重要环节。Xdebug IDE的步进调试适合定位逻辑错误性能分析工具适合识别性能瓶颈日志分析适合排查线上问题。把这几样工具用好开发和运维效率都会提升不少。