開発環境ではエラー表示、本番ではエラー非表示。だけどPHPのエラーログは記録してほしい。
CIにはENVIRONMENT
というそれらしい定数があるので、これをproduction
にすればいいんだろうなって思ってました。
すると、エラー出力と一緒にログ出力も消えます。やったね。
error_reporting(0)
PHPのマニュアルを読むと、display_errors
という設定が見つかります。
display_errors string
エラーをHTML出力の一部として画面に出力するかどうかを定義します。
CodeIgniterでもこれを使って画面出力を抑制するんでしょうね。
if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
error_reporting integer
エラー出力レベルを設定します。
マニュアルにしては説明が足りない気がしますが、これはstdoutやログに渡る前にエラーをフィルタする設定です。
error_reporting(0)
と書くと、全てのエラーをフィルタして出力しない、という意味になります。
CI「本番環境だって?じゃあエラー出力全部切るね!」
なお、v3.0ではdisplay_errors
を変更するようになっています。
CodeIgniterの例外ハンドラ
if ( ! function_exists('_exception_handler'))
{
function _exception_handler($severity, $message, $filepath, $line)
{
// We don't bother with "strict" notices since they tend to fill up
// the log file with excess information that isn't normally very helpful.
// For example, if you are running PHP 5 and you use version 4 style
// class functions (without prefixes like "public", "private", etc.)
// you'll get notices telling you that these have been deprecated.
if ($severity == E_STRICT)
{
return;
}
$_error =& load_class('Exceptions', 'core');
// Should we display the error? We'll get the current error_reporting
// level and add its bits with the severity bits to find out.
if (($severity & error_reporting()) == $severity)
{
$_error->show_php_error($severity, $message, $filepath, $line);
}
// Should we log the error? No? We're done...
if (config_item('log_threshold') == 0)
{
return;
}
$_error->log_exception($severity, $message, $filepath, $line);
}
}
CIは独自に例外ハンドラを設定してエラーを表示していますが、ここもerror_reporting
だけを見ています。
display_errors = Off
であればerror_reporting
に関わらず非表示にしてほしいですね。
なお、v3.0ではdisplay_errors
を考慮するようになっています。
おまけ:致命的なエラー
ここまで話してきたログというのはPHPのエラーログですが、CIにもエラーログがあります。こちらは(今の実装では)error_reporting
に関わらず記録されるので、これがあればPHPのエラーログがなくても、というところはあります。
ただ現状CodeIgniterは致命的なエラーをキャッチするためのシャットダウンハンドラが用意されていないため、致命的なエラーやそれに変換されるExceptionはCIのログに引っかからないという問題があります。これもv3.0では(ry
なおPHP初期化中のエラーはそれでもキャッチできませんが、error_reporting
を変更するPHPコードも実行される前なので、これはphp.iniを適切に設定しましょう。
どうするといい?
どれも CodeIgniter 3.0 で改善されています。
が、互換性のない変更点も少なくないようですから、アップグレードガイド(英語)をご参照ください。
参考
http://stackoverflow.com/questions/1911920/does-php-error-reporting0-have-any-effect-on-logging-information
http://www.slideshare.net/noldor/code-igniter-27122684