说起 profiler,老派的 php 程序员会选 xdebug,新派的 php 程序员会选 xhprof,不过我们公司的服务器上都没装,于是我写了这个「poor man php profiler」。 既然不用 xdebug 和 xhprof,我们就要自己找 profiler 的数据源才行。好在 php 本身支持慢日志,而
说起 profiler,老派的 php 程序员会选 xdebug,新派的 php 程序员会选 xhprof,不过我们公司的服务器上都没装,于是我写了这个「poor man php profiler」。
既然不用 xdebug 和 xhprof,我们就要自己找 profiler 的数据源才行。好在 php 本身支持慢日志,而且里面包含了调用栈信息,还包含了文件路径和具体的行号:
slow
理论上不用写什么工具,把这个日志从前到后看一遍就能发现系统哪里慢,但我们人穷志不短,能通过工具提升一点效率总是好的。工具写起来其实很简单,大概思路:扫描日志,把数据汇总,看看哪一个文件的哪一行出现的次数多,八成就是短板所在(当然要除去一些公共的入口文件)。下面就是源代码:
#!/bin/bashusage() { echo usage: $0 --log=}eval set -- $( getopt -q -o h -l context:,log:,help -- $@)while true; do case $1 in --context) context=$2; shift 2;; --log) log=$2; shift 2;; -h|--help) usage; exit 0;; --) break;; esacdoneif [[ -z $log ]]; then usage exit 1fic=${context:-5}awk ' $1 ~ 0x && $3 ~ / { files[$3]++ } end { for (file in files) { print files[file], file | sort -nr } }' $log | while ifs= read count data; do ifs=: data=($data) file=${data[0]} line=${data[1]} echo file: $file [count: $count] cat -n $file | grep -p -c $c --color=always ^\s*$line\t.* echodone
为了提升用户体验,我加了一些必要的色彩提示,最终的效果如下:
profiler
最后,需要提醒大家的是:因为要扫描慢日志,所以如果文件体积非常大的话,那么效率会很低下。建议定期切分日志,具体可以参考我以前写的:被遗忘的logrotate。
原文地址:poor man php profiler, 感谢原作者分享。