errorhandler.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /**
  3. * Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. namespace OC\Log;
  9. use OC\Log as LoggerInterface;
  10. class ErrorHandler {
  11. /** @var LoggerInterface */
  12. private static $logger;
  13. public static function register() {
  14. $handler = new ErrorHandler();
  15. set_error_handler(array($handler, 'onError'));
  16. register_shutdown_function(array($handler, 'onShutdown'));
  17. set_exception_handler(array($handler, 'onException'));
  18. }
  19. public static function setLogger(LoggerInterface $logger) {
  20. self::$logger = $logger;
  21. }
  22. //Fatal errors handler
  23. public static function onShutdown() {
  24. $error = error_get_last();
  25. if($error && self::$logger) {
  26. //ob_end_clean();
  27. $msg = $error['message'] . ' at ' . $error['file'] . '#' . $error['line'];
  28. self::$logger->critical($msg, array('app' => 'PHP'));
  29. }
  30. }
  31. // Uncaught exception handler
  32. public static function onException($exception) {
  33. $msg = $exception->getMessage() . ' at ' . $exception->getFile() . '#' . $exception->getLine();
  34. self::$logger->critical($msg, array('app' => 'PHP'));
  35. }
  36. //Recoverable errors handler
  37. public static function onError($number, $message, $file, $line) {
  38. if (error_reporting() === 0) {
  39. return;
  40. }
  41. $msg = $message . ' at ' . $file . '#' . $line;
  42. self::$logger->warning($msg, array('app' => 'PHP'));
  43. }
  44. }