LoginSignup
2
2

More than 5 years have passed since last update.

CakePHP2で開発時もNoticeなどをログファイルに保存したい

Posted at

CakePHP2で開発時もNoticeなどをログファイルに保存したい

前提

  • CakePHP2系はdebugが0でないときはNoticeなどは画面への表示のみでログファイルには出力されない
  • 開発時はログファイルをTail系ツールでチェックするようにしたい
  • ExceptionNotifierErrorHandlerを設定すればメールが飛んでくるが、そもそも開発時にExceptionNotifierErrorHandlerは使いたくない(メールボックスがあふれる恐れあり)

変更内容

app/Lib/Error/AppErrorHandler.php

<?php

App::uses('ErrorHandler', 'Error');
App::uses('CakeLog', 'Log');

class AppErrorHandler extends ErrorHandler {
    /**
     * デバッグ時でもログファイルに出力する
     */
    public static function handleError($code, $description, $file = null, $line = null, $context = null) {
        $result = parent::handleError($code, $description, $file, $line, $context);
        $debug = Configure::read('debug');
        if($debug) {
            if(error_reporting() !== 0) {
                $errorConfig = Configure::read('Error');
                list($error, $log) = self::mapErrorCode($code);
                if($log !== LOG_ERR) {
                    $message = $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
                    if (!empty($errorConfig['trace'])) {
                        $trace = Debugger::trace(array('start' => 1, 'format' => 'log'));
                        $message .= "\nTrace:\n" . $trace . "\n";
                    }
                    CakeLog::write($log, $message);
                }
            }
        }
        return $result;
    }
}

app/Config/bootstrap.php

// 以下を追加
App::uses('AppErrorHandler', 'Lib/Error');
Configure::write('Error.handler', 'AppErrorHandler::handleError');

備考

  • 本番環境ではExceptionNotifierErrorHandlerを使いたい場合は環境変数などをチェックして切り替えたりする必要があります
2
2
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
2
2