ErrorLogHandler.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use Monolog\Formatter\LineFormatter;
  12. use Monolog\Logger;
  13. /**
  14. * Stores to PHP error_log() handler.
  15. *
  16. * @author Elan Ruusamäe <glen@delfi.ee>
  17. */
  18. class ErrorLogHandler extends AbstractProcessingHandler
  19. {
  20. const OPERATING_SYSTEM = 0;
  21. const SAPI = 4;
  22. protected $messageType;
  23. protected $expandNewlines;
  24. /**
  25. * @param int $messageType Says where the error should go.
  26. * @param int $level The minimum logging level at which this handler will be triggered
  27. * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
  28. * @param Boolean $expandNewlines If set to true, newlines in the message will be expanded to be take multiple log entries
  29. */
  30. public function __construct($messageType = self::OPERATING_SYSTEM, $level = Logger::DEBUG, $bubble = true, $expandNewlines = false)
  31. {
  32. parent::__construct($level, $bubble);
  33. if (false === in_array($messageType, self::getAvailableTypes())) {
  34. $message = sprintf('The given message type "%s" is not supported', print_r($messageType, true));
  35. throw new \InvalidArgumentException($message);
  36. }
  37. $this->messageType = $messageType;
  38. $this->expandNewlines = $expandNewlines;
  39. }
  40. /**
  41. * @return array With all available types
  42. */
  43. public static function getAvailableTypes()
  44. {
  45. return array(
  46. self::OPERATING_SYSTEM,
  47. self::SAPI,
  48. );
  49. }
  50. /**
  51. * {@inheritDoc}
  52. */
  53. protected function getDefaultFormatter()
  54. {
  55. return new LineFormatter('[%datetime%] %channel%.%level_name%: %message% %context% %extra%');
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. protected function write(array $record)
  61. {
  62. if ($this->expandNewlines) {
  63. $lines = preg_split('{[\r\n]+}', (string) $record['formatted']);
  64. foreach ($lines as $line) {
  65. error_log($line, $this->messageType);
  66. }
  67. } else {
  68. error_log((string) $record['formatted'], $this->messageType);
  69. }
  70. }
  71. }