<?php
// 1. 回報所有錯誤等級
error_reporting(E_ALL);
// 2. 螢幕顯示錯誤(開發環境用)
ini_set('display_errors', '1');
// 3. 同時寫入錯誤日誌檔案
ini_set('error_log', __DIR__ . '/logs/php_error.log');
生產環境絕不應直接顯示錯誤給使用者,會洩露路徑、資料庫結構、敏感變數等資訊。
<?php
// 共用設定
error_reporting(E_ALL);
ini_set('error_log', __DIR__ . '/logs/php_error.log');
// 依環境決定是否顯示
$isProduction = (getenv('APP_ENV') ?? 'development') === 'production';
ini_set('display_errors', $isProduction ? '0' : '1');
// 生產環境可顯示友善錯誤頁面
if ($isProduction) {
set_error_handler(function ($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) return false; // @ 抑制的錯誤不處理
http_response_code(500);
require __DIR__ . '/templates/500.php';
exit;
});
set_exception_handler(function ($e) {
http_response_code(500);
require __DIR__ . '/templates/500.php';
exit;
});
}
| 常數 | 涵蓋範圍 | 建議 |
|---|---|---|
E_ALL | 所有錯誤、警告、通知、嚴格標準、Deprecated | 開發/測試環境推薦 |
E_ERROR | E_WARNING | E_PARSE | 僅嚴重錯誤、警告、解析錯誤 | 生產環境記錄用 |
E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT | 排除通知、棄用、嚴格標準 | 舊專案過渡期 |
logs/ 需 Web 使用者(www-data/apache)可寫,建議 chmod 775 + 群組寫入。logrotate 每日切割,保留 30 天,避免磁碟爆滿。<?php
// JSON 格式錯誤日誌(可放入自訂 error handler)
function logErrorJson(int $severity, string $message, string $file, int $line): void
{
$log = [
'time' => date('c'),
'level' => errorLevelToString($severity),
'message' => $message,
'file' => $file,
'line' => $line,
'trace' => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5),
'request' => [
'method' => $_SERVER['REQUEST_METHOD'] ?? 'CLI',
'uri' => $_SERVER['REQUEST_URI'] ?? '',
'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
],
];
error_log(json_encode($log, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}
function errorLevelToString(int $level): string
{
return match ($level) {
E_ERROR => 'ERROR',
E_WARNING => 'WARNING',
E_PARSE => 'PARSE',
E_NOTICE => 'NOTICE',
E_CORE_ERROR => 'CORE_ERROR',
E_CORE_WARNING => 'CORE_WARNING',
E_COMPILE_ERROR => 'COMPILE_ERROR',
E_COMPILE_WARNING => 'COMPILE_WARNING',
E_USER_ERROR => 'USER_ERROR',
E_USER_WARNING => 'USER_WARNING',
E_USER_NOTICE => 'USER_NOTICE',
E_STRICT => 'STRICT',
E_RECOVERABLE_ERROR => 'RECOVERABLE_ERROR',
E_DEPRECATED => 'DEPRECATED',
E_USER_DEPRECATED => 'USER_DEPRECATED',
default => 'UNKNOWN',
};
}
display_errors=1 + error_log 同步寫檔,即時除錯。display_errors=0 + 完整 error_log + 自訂錯誤處理器回傳友善頁面。