ログをFirebugのコンソールへ出力してみる。

これは何?

次のようなスクリプトを書いたときに・・・

<?php
include_once dirname(__FILE__) . '/__init__.php';
Rhaco::import('LoggerPublisherFirebug');      // 追加してるのはここと。
LoggerPublisherFirebug::initialize(true);     // ここだけ。

class Test{
	var $v_int    = 99;
	var $v_string = "string";
	var $v_array = array(1,2,3);
	var $v_hash = array("keyA"=>111,"keyB"=>"222");
}
$o = new Test();
Logger::info($o);
?>

firebugのコンソールタブに以下が出力されます。

文字列以外(オブジェクトや配列)は展開することもできます。
jsonJavascriptに展開してます)

ただ、欠点があります。
firebugが要素をソートして表示するので、順序がでたらめになることがあります。場合によっては、使いづらいです。なんとかならないものか・・・

ということで、json展開しないときはこんな感じ。

LoggerPublisherFirebug

使い方は簡単。
1ファイル追加&2行追加

Rhaco::import('LoggerPublisherFirebug');
LoggerPublisherFirebug::initialize();
又は、
LoggerPublisherFirebug::initialize(true);  // json展開するとき。

クラス本体は。
library/LoggerPublisherFirebug.php

<?php
Rhaco::import('util.Logger');
Rhaco::import('tag.model.TemplateFormatter');

/**
 * ログをFirefoxコンソールに出力する。
 *
 * @author goungoun
 * @license New BSD License
 * @copyright Copyright 2006- rhaco project. All rights reserved.
 */
class LoggerPublisherFirebug{
	function error($log)     { $this->_output($log, 'error'); }
	function warning($log)   { $this->_output($log, 'warn'); }
	function info($log)      { $this->_output($log, 'info'); }
	function debug($log)     { $this->_output($log, 'debug'); }
	function deep_debug($log){ $this->_output($log, 'debug'); }
	function _output($log, $type){
		$levels = Logger::getLevelValues();
		$out1 = sprintf("[%s %s]:[%s:%d] ",$levels[$log->getLevel()],$log->getTime("H:i:s"),$log->getFile(),$log->getLine());
		$out1 = TemplateFormatter::getJsDocument($out1);
		$value = $log->getValue(false);
		if(!is_string($value) && Rhaco::getVariable("LOGGER_PUBLISHER_FIREBUG_JSON")){
			$json = @json_encode($value);	// @ で、recursive な変数をエンコードしたときのWarning抑制
			printf('<script>(function(){ $__rhacojson__=%s; console.%s("%s", $__rhacojson__); })()</script>', $json, $type, $out1);
		}else{
			$value = $log->getValue(true);
			$out2 = TemplateFormatter::getJsDocument($value);
			printf('<script>console.%s("%s", "%s")</script>', $type, $out1, $out2);
		}
	}

	/**
	 * initialize
	 *
	 * 画面への出力を抑制するには、Logger::disableDisplay() を別途Callしてください。
	 * json_encodeを使ってます。これが無い場合、$json_flg=trueとしてもfalseで動作します。
	 *
	 * @static
	 * @param bool $json_flg ログ対象が文字列以外のとき、javascriptの変数に変換して表示するか?
	 */
	function initialize($json_flg=false){
		if(!function_exists('json_encode')) $json_flg = false;
		Rhaco::setVariable("LOGGER_PUBLISHER_FIREBUG_JSON", $json_flg);
		Logger::setPublisher(new LoggerPublisherFirebug());
	}
}

?>

補足事項

画面のログ出力を止めるときは、Logger::enableDisplay(); をCallします。
ただし、現行のrhacoは、自己参照している配列をログ出力しようとするとFatalエラーになるので、注意が必要です。
Loggerで自己参照してる変数を出力するとエラーになる。 - gounx2の日記