LoginSignup
13
12

More than 5 years have passed since last update.

[FuelPHP] ReferectionClassを使ってProfilerを無理やりLogに出力する

Last updated at Posted at 2014-12-10

概要

FuelPHPでプロファイルを見たいときにはPHP Quick ProfilerをベースにしたProfilerが一番簡単だが、ファイルやログに出力できない?のが非常に使いにくい。

特にAPI Serverなどを開発している時にはQuick Profilerなんて見れない。
↓他の人はfuel/core/classes/profiler.phpを置き換えたりしているが、コアライブラリを置き換えるのはなるべくやめたい。

そこで、FuelPHPのEventReflectionClassを使ってプロファイルをログに出力することをやってみる。

Reflection Class

ReflectionClassはPHP5から導入されている。

情報工学においてリフレクション (reflection) とは、プログラムの実行過程でプログラム自身の構造を読み取ったり書き換えたりする技術のことを指す。by wikipedia

ようは外部からクラスの中身をいじったりできる機能である。

コード

方針としてはReflectionClassでProfilerクラスの変数を外部からアクセス可能な状態にして必要な情報を取得する。

ログを出力する場所はリクエストを送った後の終了時にする。
そこでFuelPHPのEventクラスはリクエストを送った後の終了時のイベントハンドラを登録することができる。

実際にはapp/config/event.phpに以下のコードを置く。

<?php

return array(
	'fuelphp' => array(
		'shutdown' => function() {
			$ref = new ReflectionClass('Profiler');
			$prop = $ref->getProperty('profiler');
			$prop->setAccessible(true);
			$profiler = $prop->getValue();
			if ($profiler) {
				$profiler->db = $profiler;
				$profiler->gatherConsoleData();
				$profiler->gatherPathData();
				$profiler->gatherFileData();
				$profiler->gatherMemoryData();
				$profiler->gatherQueryData();
				$profiler->gatherSpeedData();
				\Log::info(print_r($profiler->output, true));
			}
		},
	),
);
(
    [logs] => Array
        (
            [console] => Array
                (
                    [0] => Array
                        (
                            [data] => 1.412 ms
                            [type] => speed
                            [name] => Fuel\Core\Profiler::init Start
                        )

                    [1] => Array
                        (
                            [data] => 2.361 ms
                            [type] => speed
                            [name] => Fuel\Core\Fuel::init End
                        )

                    [2] => Array
                        (
                            [data] => 2.433 ms
                            [type] => speed
                            [name] => Fuel\Core\Uri::__construct Start
                        )
...
13
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
12