LoginSignup
19
18

More than 5 years have passed since last update.

chrome-extensionのChromePHPを使用してchromeからログを見る

Posted at

chromePHPはPHPのログをコンソールに吐き出せるようにするツールです。

chrome-extensionをインストールする

ChromePHP

インストールするだけ

使い方

公式ドキュメントのまんまでOK
include_pathをとおして置くと何かと楽

include 'ChromePhp.php';
ChromePhp::log('hello world');
ChromePhp::log($_SERVER);

// using labels
foreach ($_SERVER as $key => $value) {
    ChromePhp::log($key, $value);
}

// warnings and errors
ChromePhp::warn('this is a warning');
ChromePhp::error('this is an error');

でもこのままだとどこでログが出力されたかわからないのでちょっとカスタマイズする

My_Log.php
class My_Log {
    /**
     * クロムのコンソールログに出力するようのログ ※要chrome extension chromePHP
     * @link http://www.chromephp.com/
     * @param $message mixed 表示したいログの内容
     * @param $ident string ログの先頭に出力するプレフィックス文字列
     * @param $level int ChromePHPのログ出力フォーマットレベル
     * @return void
     **/
    public static function console($message, $key = null, $level = 'info') {

        $targetBackTrace = array();

        foreach (debug_backtrace() as $i => $val) {
            // 対象クラスと一致するので対象のバックトレース情報を付与する
            if ($i == $val['class']) {
                $targetBackTrace = $val;
                $filePath  = explode(DIRECTORY_SEPARATOR, $val['file']);
                $fileShort = array_slice($filePath, (count($filePath) - 3));
                $file      = implode(DIRECTORY_SEPARATOR, $fileShort);
                $key       = sprintf('trace [%s:%s]', $file, $val['line']);
                break;
            }
        }

        require_once 'ChromePhp.php';
        switch ($level) {
            case 'info':
                if (is_null($key)) {
                    return ChromePhp::log($message);
                }
                ChromePhp::log($key, $message);
                break;
            case 'warm':
                if (is_null($key)) {
                    return ChromePhp::warn($message);
                }
                ChromePhp::warn($key, $message);
                break;
            case 'error':
                if (is_null($key)) {
                    return ChromePhp::error($message);
                }
                ChromePhp::error($key, $message);
                break;
        }
    }

}

大体今時はMVCなのでbacktraceから同一のクラスを見つけた場合の情報を取得している。
使い方はシンプル

hoge.php
My_Log::console($_SERVER);

以上

19
18
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
19
18