您可以通过实现自定义ErrorHandler
和覆盖某些AppKernel
方法来做到这一点。例如:
class AppKernel
{
protected $prodErrorHandler;
public function init()
{
if ($this->debug) {
ini_set('display_errors', 1);
error_reporting(-1);
DebugUniversalClassLoader::enable();
ErrorHandler::register();
if ('cli' !== php_sapi_name()) {
ExceptionHandler::register();
}
} else {
ini_set('display_errors', 0);
error_reporting(-1);
$this->prodErrorHandler = new CustomErrorHandler();
set_error_handler(array($this->prodErrorHandler, 'handle'));
}
}
public function boot()
{
$booted = $this->booted;
parent::boot();
if (!$booted && $this->prodErrorHandler !== null && $this->container->has('logger')) {
$this->prodErrorHandler->setLogger($this->container->get('logger'));
}
}
// ... other methods
}
class CustomErrorHandler
{
protected $logger;
protected $buffer = array();
public function setLogger($logger)
{
$this->logger = $logger;
foreach ($this->buffer as $error) {
$this->logger->warning($error);
}
$this->buffer = array();
}
public function handle($level, $message, $file, $line, $context)
{
if (error_reporting() & $level) {
$error = new \ErrorException(sprintf('%s: %s in %s line %d', isset($this->levels[$level]) ? $this->levels[$level] : $level, $message, $file, $line));
if ($this->logger !== null) {
$this->logger->warning($error);
} else {
$this->buffer[] = $error;
}
return true; // this would skip logging to file etc. Return false to just log and pass error handling to other handlers
} else {
return false;
}
}
}
类似的事情也可以用单独的 Bundle 完成,但它可以“跳过”在 bundle 注册之前发生的一些错误。
如果您使用Monolog 1.6
或更高版本,您还可以使用Monolog\ErrorHandler
logger 来注册错误、未处理的异常和致命错误。