TOOL更新_今日はLog出力クラスを作り始めた。
1.今日はLog出力クラスを作り始めた。
このやり方(デバックログと例外ログとSQLログの3本立て。オラクルの人(自動作成◎自動生成対象外だけど。使う気さえあれば使えるので。)やレンタルサーバの人はSQLログを自分で出したいだろうから。まだ実験中なのでコーディング規約には沿っていないけど、徐々に、このページを直接直していくことにする。
■使い方はこんな感じ
protected $_logger = null; // ログ出力オブジェクト ・・・ // 前処理 protected function _preDo() { // ログ $this->_logger = new AppLogr($this->_getDebugDir(), $this->_getDebugFlg()); ・・・ // 入力データダンプ if ($this->_getStartDebugFlg() == true) { $this->_logger->outDbgLog('[START]: _sess', $this->_sess); // セッションデータ(array) $this->_logger->outDbgLog('[START]: _o', $this->_o); // 画面入力データ(array) } } ・・・ // 共通アクション(実装ロジック) public function _commAct() { ・・・ // ZENDなどが出す例外 } catch (Exception $e) { if ($this->_logger != null) { $this->_logger->outErrLog('The Error occurred. ' . $e->getFile().":". $e->getLine().":".$e->getMessage(), Zend_Log::ERR); echo ' Message: ' . 'The Error occurred. ' . "<br />\n"; } else { echo ' Message: ' . 'The Error occurred. And logger = null.' . "<br />\n"; } // DB rollback(継承先でDB使わないときは何もしない) $this->_dbRollback(); exit; } }
■Log出力クラスはこれ
<?php // ============================================================= // 2010 kaz PHP自動作成お助けTOOL.(http://kazpgm.ddo.jp/) Start // 修正BSDライセンス。 // ============================================================= class AppLogr { protected $_debugLogger = null; // DEBUGログ出力オブジェクト protected $_sqlLogger = null; // SQLログ出力オブジェクト protected $_errorLogger = null; // ERRORやWARNINGログ出力オブジェクト protected $_logDir = null; // ログ出力ディレクトリ protected $_debugFlg = true; // DEBUG出力フラグ protected $_creLoggerDebugFlg = false; // Debug用Loggerフラグ protected $_creLoggerSqlFlg = false; // Sql用Loggerフラグ protected $_creLoggerErrorFlg = false; // ERRORやWARNING用Loggerフラグ public function __construct($logDir = null, $debugFlg = true) { if ($debugFlg == null) { // DEBUGフラグがnull $debugFlg = false; } if ($logDir == null || $logDir == '') { // ログDIRがない場合 throw new SysException('Invalid argument. use AppLogr(not null, not null)'); } $this->_logDir = $logDir; $this->_debugFlg = $debugFlg; } // DEBUGログ出力オブジェクト作成 protected function _getDebugLogger() { if ($this->_creLoggerDebugFlg == false) { // LoggerDebugフラグOFF // DEBUGログ $this->_debugLogger = $this->_getLogger($this->_logDir . date('Ymd') . '_debug.log'); $this->_creLoggerDebugFlg = true; // LoggerDebugフラグON } return $this->_debugLogger; } //Sqlグ出力オブジェクト作成 protected function _getSqlLogger() { if ($this->_creLoggerSqlFlg == false) { // LoggerDebugフラグOFF // DEBUGログ $this->_sqlLogger = $this->_getLogger($this->_logDir . date('Ymd') . '_sql.log'); $this->_creLoggerSqlFlg = true; // LoggerDebugフラグON } return $this->_sqlLogger; } // ERRORやWARNINGログ出力オブジェクト作成 protected function _getErrorLogger() { if ($this->_creLoggerErrorFlg == false) { // LoggerErrorフラグOFF // ERRORログ $this->_errorLogger = $this->_getLogger($this->_logDir . date('Ymd') . '_error.log'); $this->_creLoggerErrorFlg = true; // LoggerErrorフラグON } return $this->_errorLogger; } // ログ出力オブジェクト作成 protected function _getLogger($flName) { // ERRORログ $logger = new Zend_Log(); $logger->setEventItem("timestamp", date("Y/m/d H:i:s")); $errorWriter = new Zend_log_Writer_Stream($flName); // 出力フォーマット $format = '%timestamp% %priorityName% (%priority%): %message%' . PHP_EOL; $formatter = new Zend_Log_Formatter_Simple($format); $errorWriter->setFormatter($formatter); $logger->addWriter($errorWriter); return $logger; } // DEBUGログ出力 public function outDbgLog($id, $msg = PHP_EOL) { if ($this->_debugFlg != true) { // デバックフラグがtrue以外は何もしない。 return; } $log = ''; $typ = gettype($msg); if ($typ == 'string') { // stringはそのまま出力 $log .= $msg . ' '; } else if ($typ == 'double') { // doubleはそのまま出力 $log .= $msg . ' '; } else if ($typ == 'boolean') { // booleanはtrue、false出力 $log .= $msg ? 'true' : 'false' . ' '; } else { // その他はvar_dumpまたはprint_rして出力 // var_dumpより print_rのほうが見やすいので。(print_r($msg, true);はob_start関連がいらない。) //ob_start(); //var_dump($msg); //$dmp =ob_get_contents(); //ob_end_clean(); //$log .= $dmp; $dmp = print_r($msg, true); $log .= $dmp; } // PHPファイル名とライン行を求める $backtrace = debug_backtrace(); $prg = ''; foreach($backtrace as $key => $vals ){ $phpname = preg_match('/[_a-zA-Z0-9\.]+\.[^\.]+$/', $vals["file"], $match) ? $match[0] : $vals["file"]; $prg .= $phpname. " line=" .$vals["line"] . ' '; break; // 最初の1件だけにしておく } $log = $prg . ': ' .$log; // DEBUGログ出力 list($mnow,$now) = split(' ',microtime()); $this->_getDebugLogger()->log($mnow . ' ' . $id . ': ' . $log , Zend_Log::DEBUG); } // Sqlログ出力 public function outSqlLog($id, $sql = PHP_EOL) { if ($this->_debugFlg != true) { // デバックフラグがtrue以外は何もしない。 return; } $log = $sql . ' '; // PHPファイル名とライン行を求める $backtrace = debug_backtrace(); $prg = ''; // [2]固定にする。[0]はDbManagerの_outSqlLogメソッド、[1]はDbManagerの該当メソッド、 // [2]がDbManagerを呼び出したメソッド $phpname = preg_match('/[_a-zA-Z0-9\.]+\.[^\.]+$/', $backtrace[2]["file"], $match) ? $match[0] : $backtrace[2]["file"]; //$prg .= $backtrace[2]["file"]. " line=" .$backtrace[2]["line"] . ' '; $prg .= $phpname. " line=" .$backtrace[2]["line"] . ' '; $log = $prg . ': ' .$log; // DEBUGログ出力 list($mnow,$now) = split(' ',microtime()); $this->_getSqlLogger()->log($mnow . ' ' . $id . ': ' . $log , Zend_Log::DEBUG); } // ERRORやWARNINGログ出力 public function outErrLog($msg, $priority) { // PHPファイル名とライン行を求める $backtrace = debug_backtrace(); $prg = ''; foreach($backtrace as $key => $vals ){ $phpname = preg_match('/[_a-zA-Z0-9\.]+\.[^\.]+$/', $vals["file"], $match) ? $match[0] : $vals["file"]; $prg .= $phpname. " line=" .$vals["line"] . ' '; } $log = $prg . ': ' .$msg; list($mnow,$now) = split(' ',microtime()); $this->_getErrorLogger()->log($mnow . ' ' . $log, $priority); } // DEBUGフラグ設定 public function setDebugFlg($debugFlg = true) { $this->_debugFlg = $debugFlg; } } // ============================================================= // 2010 kaz PHP自動作成お助けTOOL.(http://kazpgm.ddo.jp/) End // 修正BSDライセンス。 // =============================================================
■その他:ボツにしたもの
・これならZend_Log::DEBUG、Zend_Log::ERRなど($priority)を見て、勝手にlogを振り分けてくれるのでいいなと思った。が、サイズ0のlogができてしまう。(1つ吐き出すとdebug.log、info.log、error.logを作る仕様みたいだ)いらないファイルを吐き出されれるのはうれしくない。のでやめた。<=備忘録
protected function creLogger() {
$logger = new Zend_Log();
// 出力フォーマット
$format = '%timestamp% %priorityName% (%priority%): %message%' . PHP_EOL;
$formatter = new Zend_Log_Formatter_Simple($format);
$logger->setEventItem("timestamp", date("Y/m/d H:i:s"));$debugWriter = new Zend_log_Writer_Stream(APP.'/log/debug.log');
$debugFilter = new Zend_Log_Filter_Priority(Zend_Log::DEBUG ,"==");
$debugWriter->addFilter($debugFilter);
$debugWriter->setFormatter($formatter);
$logger->addWriter($debugWriter);$infoWriter = new Zend_log_Writer_Stream(APP.'/log/info.log');
$infoStartFilter = new Zend_Log_Filter_Priority(Zend_Log::INFO);
$infoEndFilter = new Zend_Log_Filter_Priority(Zend_Log::WARN ,">=");
$infoWriter->addFilter($infoStartFilter);
$infoWriter->addFilter($infoEndFilter);
$infoWriter->setFormatter($formatter);
$logger->addWriter($infoWriter);$errorWriter = new Zend_log_Writer_Stream(APP.'/log/error.log');
$errorFilter = new Zend_Log_Filter_Priority(Zend_Log::ERR);
$errorWriter->addFilter($errorFilter);
$errorWriter->setFormatter($formatter);
$logger->addWriter($errorWriter);$this->_logger = $logger;
}protected function outErrLog($msg, $priority) {
$this->_logger->log($msg, $priority);
}
その他2:備忘録
・$e->getFile().":". $e->getLine()で例外発生PGMとLINEがわかる。
01/18 21:00-03:00
01/19 20:00-21:00
01/20 21:00-23:00
01/21 01:00^01:30 オブジェクトはver_dump()よりprint_r()のほうが見やすい
03/01 01:00-01:30 print_r($msg, true);はob_start関連がいらない。ということで修正した。
03/09 01:30-01:40 DBをZend_dbのDbManagerクラスにした。そこでSQL文をLOG出力することにしたので。SQLログ出力処理を追加した。
6/10 20:10-20:40 次期バージョン最新PGMに置き換えた。
7/21 0:30-0:40 http://d.hatena.ne.jp/kazpgm/20100721/1279726183(TOOL更新_AppLogr.php修正Comments)による修正。(ログにでるプログラム名がうまく取れていなかった。)。、、、、「■使い方はこんな感じ」も今の「ControllerBase.php」に合わせて、修正した。