ErrorLogHandler.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php declare(strict_types=1);
  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\Formatter\FormatterInterface;
  13. use Monolog\Logger;
  14. /**
  15. * Stores to PHP error_log() handler.
  16. *
  17. * @author Elan Ruusamäe <glen@delfi.ee>
  18. */
  19. class ErrorLogHandler extends AbstractProcessingHandler
  20. {
  21. public const OPERATING_SYSTEM = 0;
  22. public const SAPI = 4;
  23. /** @var int */
  24. protected $messageType;
  25. /** @var bool */
  26. protected $expandNewlines;
  27. /**
  28. * @param int $messageType Says where the error should go.
  29. * @param bool $expandNewlines If set to true, newlines in the message will be expanded to be take multiple log entries
  30. */
  31. public function __construct(int $messageType = self::OPERATING_SYSTEM, $level = Logger::DEBUG, bool $bubble = true, bool $expandNewlines = false)
  32. {
  33. parent::__construct($level, $bubble);
  34. if (false === in_array($messageType, self::getAvailableTypes(), true)) {
  35. $message = sprintf('The given message type "%s" is not supported', print_r($messageType, true));
  36. throw new \InvalidArgumentException($message);
  37. }
  38. $this->messageType = $messageType;
  39. $this->expandNewlines = $expandNewlines;
  40. }
  41. /**
  42. * @return int[] With all available types
  43. */
  44. public static function getAvailableTypes(): array
  45. {
  46. return [
  47. self::OPERATING_SYSTEM,
  48. self::SAPI,
  49. ];
  50. }
  51. /**
  52. * {@inheritDoc}
  53. */
  54. protected function getDefaultFormatter(): FormatterInterface
  55. {
  56. return new LineFormatter('[%datetime%] %channel%.%level_name%: %message% %context% %extra%');
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. protected function write(array $record): void
  62. {
  63. if (!$this->expandNewlines) {
  64. error_log((string) $record['formatted'], $this->messageType);
  65. return;
  66. }
  67. $lines = preg_split('{[\r\n]+}', (string) $record['formatted']);
  68. if ($lines === false) {
  69. throw new \RuntimeException('Failed to preg_split formatted string: '.preg_last_error().' / '.preg_last_error_msg());
  70. }
  71. foreach ($lines as $line) {
  72. error_log($line, $this->messageType);
  73. }
  74. }
  75. }