ErrorLogHandler.php 2.5 KB

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