上一篇文章里,我們介紹了如何基於xhprof擴展來分析PHP性能,並記錄到日志里,最后使用xhprof擴展自帶的UI在web里展示出來。本篇文章將講述2個知識點:
- 使用xhgui代替xhprof的默認UI界面,更便於分析
- 使用tideways擴展替換xhprof擴展
使用更漂亮的UI: xhgui
xhgui支持 XHProf, Uprofiler或者Tideways 擴展,也就是說,只要安裝了這幾種擴展中的一種即可。
本次測試中,實際使用了tideways擴展(切換為XHProf擴展后web里看不到數據,原因未知。切換為Uprofiler也沒有數據。)。
xhprof雖然來自facebook但已經很久不更新,官方源已經顯示This package is abandoned and no longer maintained(此包已廢棄,不再維護)。tideways恰好相反,一直有商業公司在維護,並且積極的支持了PHP7。兩個擴展都是開源的,綜上所述我建議大家選擇tideways來分析代碼。
安裝tideways擴展:
wget https://github.com/tideways/php-xhprof-extension/archive/v4.1.5.tar.gz -O php-xhprof-extension-4.1.5.tar.gz
tar xzf /php-xhprof-extension-4.1.5.tar.gz
cd php-xhprof-extension-4.1.5
phpize
./configure
make && make install
安裝xhgui
cd /work/
git clone https://github.com/perftools/xhgui.git xhgui
如果需要安裝中文界面的,可以:
git clone https://github.com/laynefyc/xhgui-branch.git xhgui
然后安裝xhgui依賴:
cd xhgui
php install.php
安裝需要等待幾分鍾,請耐心等待。
設置緩存目錄的權限,允許nginx創建文件:
chmod -R 777
xhgui已經把注入入口文件都寫好了,位於external/header.php
,無需我們手動去寫類似上一篇的xhprof.inc.php
注入文件。
安裝MongoDB及客戶端
xhgui 把日志寫到了MongoDB,所以使用xhgui需要安裝MongoDB服務端。此處省略安裝、啟動MongoDB服務端過程。
為提高 MongoDB 的性能,你可以運行以下指令以添加索引:
$ /usr/local/mongodb/bin/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 } )
同理,由於xhgui是PHP寫的,還需要讀取MongoDB里的數據,需要安裝MongoDB php 客戶端:
pecl install mongodb
然后在php.ini文件添加配置:
[mongo]
extension=mongo.so
查看擴展是否安裝成功:
php -m | grep mongo
然后重啟php-fpm服務。
配置xhgui
xhgui的config目錄有一個config.default.php,復制為config.php
,如果mongodb地址不是默認的,修改:
'db.host' => 'mongodb://127.0.0.1:27017',
還有修改采樣頻率,默認是1/100,測試的話改為true:
'profiler.enable' => function() {
//return rand(1, 100) === 42;
return true;
},
配置項目注入
上一篇文章中,我們介紹到,注入的入口文件可以寫到php.ini或者nginx,我建議寫在nginx配置,這樣只會影響該nginx對應的項目,而不是所有使用該php環境的項目。入口文件使用xhgui自帶的注入文件:
jifen.cc.conf
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PHP_VALUE "auto_prepend_file=/work/xhgui/external/header.php";
include fastcgi_params;
}
配置xhgui web
我們修改xhprof.test.com.conf為:
server {
listen 80;
server_name xhprof.test.com;
#root /work/xhprof/xhprof_html;
root /work/xhgui/webroot/;
index index.php index.html;
location / {
if (!-e $request_filename) {
rewrite . /index.php last;
}
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
重啟nginx服務。
我們請求幾次應用的接口,打開瀏覽器輸入http://xhprof.test.com/,可以看到:
點擊某次請求進去看詳情:
參考
1、PHP性能追蹤及分析工具xhprof的安裝與使用 - 馬新才的技術博客 - SegmentFault 思否
https://segmentfault.com/a/1190000007288664#articleHeader4
2、Tideways和xhgui打造PHP非侵入式監控平台 | 我是大熊
http://blog.it2048.cn/article-tideways-xhgui/