PHP 项目性能分析平台搭建 (tideways + xhgui+ PHP7)
发表于:2026-06-15 16:08:29浏览:1次
一:php项目性能分析平台
1:平台组成
- tideways:是有商业公司在维护,并且积极的支持了 PHP7,只是生成日志,过去 Facebook 曾经打造过一个工具 xhprof,不支持php7。
- xhgui: 一款基于 Bootstrap 的 xhprof UI 程序,xhprof 生成的日志和 tideways 生成的日志格式通用
- 说白就是不用改动你程序的代码,通过 nginx 为你程序上方在加一层监控层(产出固定日志),分析日志的出程序信息。
2:为啥搭这个平台
接手旧项目时,项目业务复杂,比如一个列表接口里面有:cookie鉴权(http请求两次java接口),redis消息队列,pdo数据库,workerman业务等业务,加新功能时,本地测试响应缓慢,没有给太多时间让你优化,最快方法用tideways查看执行的细节日志。
3:软件需要环境
- mongodb, 存储监控的日志。
- php7扩展: mongodb.so,tideways_xhprof.so
- 部署xhgui项目,php项目,用来查看要监控的项目
二:搭建步骤
1:mongodb
2:php7的mongodb扩展
如果是用宝塔,直接安装,其他情况yum或编译安装
3:php7的tideways_xhprof扩展
git clone https://github.com/tideways/php-xhprof-extension.git
cd /path/php-xhprof-extension
#安装
/www/server/php/72/bin/phpize
./configure --with-php-config=/www/server/php/72/bin/php-config
make && make install
vim /www/server/php/72/etc/php.ini
[tideways]
extension=tideways_xhprof.so
; 不需要自动加载,在程序中控制就行
tideways.auto_prepend_library=0
; 频率设置为100,在程序调用时可以修改
tideways.sample_rate=100
4:部署xhgui项目
安装 xhgui-branch(xhgui 的汉化版)
git clone https://github.com/laynefyc/xhgui-branch.git
cd xhgui-branch
# 给 cache 文件写入权限
php install.php
# 如果执行不成功 composer install,主要安装一些需要的包
修改 xhgui-branch 配置文件
<?php
return array(
...
'extension' => 'tideways_xhprof',
...
'save.handler' => 'mongodb',
'db.host' => 'mongodb://127.0.0.1:27017',
'db.db' => 'xhprof',
...
);
其他配置,可不用操作
#xhgui 默认是采集1% ,如果是排查问题时还是希望能够100%采集会比较方便。进入xhgui源码目录,修改config/config.default.php文件,
#平时仍然按1%的采样率采样,防止数据增长过快,当想调试时,就在URL中添加debug=1的参数即可。
#在xhgui/config/config.default.php中,找到profiler.enable这里,按如下修改:
#mongo
//采样率
'profiler.enable' => function() {
// url 中包含debug=1则百分百捕获
if(!empty($_GET['debug'])){
return true;
} else {
// 1%采样
return rand(1, 100) === 42;
}
},
//优化建议:可以给mongo数据表加上索引
链接。
5:启动 mongodb 并设置 xhgui 索引
# 注意如果按照的是6版本以上 用 mongosh
$ mongo
> use xhprof
> db.results.ensureIndex( { 'meta.SERVER.REQUEST_TIME' : -1 } )
> db.results.ensureIndex( { 'profile.main().wt' : -1 } )
> db.results.ensureIndex( { 'profile.main().mu' : -1 } )
> db.results.ensureIndex( { 'profile.main().cpu' : -1 } )
> db.results.ensureIndex( { 'meta.url' : 1 } )
6:xhgui 本地虚拟主机配置参考
server {
listen 80;
server_name xhgui.test;
root /www/wwwroot/xhgui-branch/webroot;
# access_log /usr/local/var/log/nginx/access.log;
error_log /usr/local/var/log/nginx/error.log;
location / {
try_files $uri $uri/ /index.php?$query_string;
index index.php index.html index.htm;
}
}
注意:如果是宝塔安装,直接添加伪静态,参照laravel的伪静态
7:监控要监控的项目
//在需要的项目中的最开始,引入文件即可
require "/www/wwwroot/xhgui.test/external/header.php";
//操作项目,即可在xhgui平台中查看数据分析性能
8:提示require(): open_basedir restriction in effect.
因为项目开启了防跨站攻击(open_basedir),不允许访问项目目录以为的目录
宝塔上可以很方便在项目上管理,
这是在项目目录 下配置的防跨站攻击
解决方法:把/www/wwwroot/xhgui.test/external/ 放进去
open_basedir=/www/wwwroot/test/:/tmp/
三:效果图



