colly_wyx
2018-04-27 74adf3a72663f151dc2c1b87ecb4ea4b0e080a50
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
/**
 * PhalApi_Helper_Tracer 全球追踪器类
 *     
 * 用于调试,追踪接口执行的情况
 *
 * @package     PhalApi\Helper
 * @license     http://www.phalapi.net/license GPL 协议
 * @link        http://www.phalapi.net/
 * @author      喵了个咪<wenzhenxi@vip.qq.com> 2017-04-15
 * @author      dogstar <chanzonghuang@gmail.com> 2017-04-15
 */
 
class PhalApi_Helper_Tracer {
 
    /**
     * @var array $timeline 时间线
     */
    protected $timeline = array();
 
    /**
     * @var array $sqls 所执行的SQL语句
     */
    protected $sqls = array();
 
    /**
     * 打点,纪录当前时间点
     * @param string $tag 当前纪录点的名称,方便最后查看路径节点
     * @return NULL
     */
    public function mark($tag = NULL) {
        if (!DI()->debug) {
            return;
        }
 
        $backTrace = debug_backtrace();
        if (empty($this->timeline)) {
            array_shift($backTrace);
        }
        // TODO 关于追踪,看下如何追踪更合适
 
        $this->timeline[] = array(
            'tag' => $tag, 
            'time' => $this->getCurMicroTime(),
            'file' => isset($backTrace[0]['file']) ? $backTrace[0]['file'] : '',
            'line' => isset($backTrace[0]['line']) ? $backTrace[0]['line'] : 0,
        );
    }
 
    /**
     * 生成报告
     * @return array
     */
    public function getStack() {
        $stack = array();
 
        $preMicroTime = NULL;
        foreach ($this->timeline as $index => $item) {
            if ($preMicroTime === NULL) {
                $preMicroTime = $item['time'];
            }
            $internalTime = $item['time'] - $preMicroTime;
            $internalTime = round($internalTime/10, 1);
 
            $stack[] = sprintf('[#%d - %sms%s]%s(%d)',
                $index, 
                $internalTime, 
                $item['tag'] !== NULL ? ' - ' . $item['tag'] : '', 
                $item['file'], 
                $item['line']
            );
        }
 
        return $stack;
    }
 
    /**
     * 获取当前毫秒时间
     * @return float
     */
    protected function getCurMicroTime() {
        return round(microtime(true) * 10000);
    }
 
    /**
     * 纪录SQL语句
     * @param string $string  SQL语句
     * @return NULL
     */
    public function sql($statement) {
        $this->sqls[] = $statement;
    }
 
    /**
     * 获取SQL语句
     * @return array
     */
    public function getSqls() {
        return $this->sqls;
    }
}