symfonyで独自loggerを実装する
WEBサーバへログイン出来ない環境でお仕事をした。
phpファイルのコピーは問題ないのだが、各サーバへ出力されたログを見ることが出来ないため、何かしらの解決策が必要になった。
各サーバで出力したログを転送したりいろいろアイディアはあったが、インフラ側でいろいろと作業が必要になるためこれは却下。
そこで、アプリケーション側だけで対処可能な、データベースへログを記録する方法をとった。以下、その方法のメモ。
ロガーの実装
方法は以下の2つがある。
1.sfLoggerを継承する
2.sfLoggerInterfaceを実装する
今回は1を選択した。
DatabaseLogger.php
<?php class DatabaseLogger extends sfLogger { protected function doLog($message, $priority) { try { $con = Propel::getConnection(); $sql = "INSERT INTO app_log(priority, message, info, timestamp) VALUES(?, ?, ?, NOW())"; $sth = $con->prepare($sql); $sth->execute(array($priority, 'Request: ' . $_SERVER['REQUEST_URI'], $message)); } catch(Exception $e) { } } }
設定ファイルの記述
factories.ymlで今回実装したロガーを利用する記述を追加する。
(sf_database_debugのところ)
logger: class: sfAggregateLogger param: level: debug loggers: sf_web_debug: class: sfWebDebugLogger param: level: debug condition: %SF_WEB_DEBUG% xdebug_logging: false web_debug_class: sfWebDebug sf_file_debug: class: sfFileLogger param: level: debug file: %SF_LOG_DIR%/%SF_APP%_%SF_ENVIRONMENT%.log file_mode: 0660 sf_database_debug: class: DatabaseLogger param: level: debug
こうすることで、データベースにログを書き出すことが出来た。