StreamHandler.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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\SimpleFormatter;
  12. use Monolog\Logger;
  13. /**
  14. * Stores to any stream resource
  15. *
  16. * Can be used to store into php://stderr, remote and local files, etc.
  17. *
  18. * @author Jordi Boggiano <j.boggiano@seld.be>
  19. */
  20. class StreamHandler extends AbstractProcessingHandler
  21. {
  22. protected $stream;
  23. protected $url;
  24. /**
  25. * @param string $stream
  26. * @param integer $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. */
  29. public function __construct($stream, $level = Logger::DEBUG, $bubble = true)
  30. {
  31. parent::__construct($level, $bubble);
  32. if (is_resource($stream)) {
  33. $this->stream = $stream;
  34. } else {
  35. $this->url = $stream;
  36. }
  37. }
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public function close()
  42. {
  43. if (is_resource($this->stream)) {
  44. fclose($this->stream);
  45. }
  46. $this->stream = null;
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. protected function write(array $record)
  52. {
  53. if (null === $this->stream) {
  54. if (!$this->url) {
  55. throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
  56. }
  57. $this->stream = @fopen($this->url, 'a');
  58. if (!is_resource($this->stream)) {
  59. $this->stream = null;
  60. throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened; it may be invalid or not writable.', $this->url));
  61. }
  62. }
  63. fwrite($this->stream, (string) $record['formatted']);
  64. }
  65. }