PHP框架是Laravel,环境linux
在项目根目录的bootstrap目录下新建profile.php:
<?php
if (extension_loaded('xhprof')) {
xhprof_enable(XHPROF_FLAGS_MEMORY | XHPROF_FLAGS_NO_BUILTINS);
register_shutdown_function(function () {
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
$xhprof_data = xhprof_disable();
file_put_contents(getXhprofDir(), formatResult($xhprof_data));
});
function getXhprofDir()
{
$path = ini_get('xhprof.output_dir') ?: '/tmp';
if (!file_exists($path)) {
mkdir($path, 0777);
}
return $path . '/' . uniqid() . '.xhprof.xhprof';
}
function formatResult($xhprof_data) {
foreach ($xhprof_data as $key => $value) {
$xhprof_data[$key]['function'] = $key;
}
$xhprof_data = array_values($xhprof_data);
$xhprof_data_json = json_encode($xhprof_data);
//去掉json_encode之后[{'a':1,'b':2},{'c':3}]俩边的[],将俩个},{之间的,逗号替换成\t,之后logstash需要用来做分隔符
return str_replace("},{", "}\\t{", substr($xhprof_data_json, 1, strlen($xhprof_data_json) - 2));
}
}
然后在bootstrap/autoload.php中引入,如果在index.php中引入的话,在php artisan的调用就要重新引入一次,所以房子autoload中。
在logstash/config下新建xhprof.conf:
input {
file {
path => "/tmp/xhprof/*.xhprof.xhprof"
}
}
filter {
split {
field => "message"
terminator => "\t"
}
json {
source => "message"
remove_field => "message"
}
}
output {
elasticsearch {
hosts => "127.0.0.1:9200"
index => "profile-%{+YYYY.MM.dd}"
}
stdout {
codec => rubydebug
}
}
启动bin/logstash -f config/xhprof.conf
最后在kibana中新增一个index pattern: profile-*