3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Log\Writer
;
13 use Zend\Log\Exception
;
14 use Zend\Log\Formatter\Simple
as SimpleFormatter
;
15 use Zend\Stdlib\ErrorHandler
;
17 class Stream
extends AbstractWriter
20 * Separator between log entries
24 protected $logSeparator = PHP_EOL
;
27 * Holds the PHP stream to log to.
31 protected $stream = null;
36 * @param string|resource|array|Traversable $streamOrUrl Stream or URL to open as a stream
37 * @param string|null $mode Mode, only applicable if a URL is given
38 * @param null|string $logSeparator Log separator string
40 * @throws Exception\InvalidArgumentException
41 * @throws Exception\RuntimeException
43 public function __construct($streamOrUrl, $mode = null, $logSeparator = null)
45 if ($streamOrUrl instanceof Traversable
) {
46 $streamOrUrl = iterator_to_array($streamOrUrl);
49 if (is_array($streamOrUrl)) {
50 parent
::__construct($streamOrUrl);
51 $mode = isset($streamOrUrl['mode']) ?
$streamOrUrl['mode'] : null;
52 $logSeparator = isset($streamOrUrl['log_separator']) ?
$streamOrUrl['log_separator'] : null;
53 $streamOrUrl = isset($streamOrUrl['stream']) ?
$streamOrUrl['stream'] : null;
56 // Setting the default mode
61 if (is_resource($streamOrUrl)) {
62 if ('stream' != get_resource_type($streamOrUrl)) {
63 throw new Exception\
InvalidArgumentException(sprintf(
64 'Resource is not a stream; received "%s',
65 get_resource_type($streamOrUrl)
70 throw new Exception\
InvalidArgumentException(sprintf(
71 'Mode must be "a" on existing streams; received "%s"',
76 $this->stream
= $streamOrUrl;
78 ErrorHandler
::start();
79 $this->stream
= fopen($streamOrUrl, $mode, false);
80 $error = ErrorHandler
::stop();
82 throw new Exception\
RuntimeException(sprintf(
83 '"%s" cannot be opened with mode "%s"',
90 if (null !== $logSeparator) {
91 $this->setLogSeparator($logSeparator);
94 if ($this->formatter
=== null) {
95 $this->formatter
= new SimpleFormatter();
100 * Write a message to the log.
102 * @param array $event event data
104 * @throws Exception\RuntimeException
106 protected function doWrite(array $event)
108 $line = $this->formatter
->format($event) . $this->logSeparator
;
109 fwrite($this->stream
, $line);
113 * Set log separator string
115 * @param string $logSeparator
118 public function setLogSeparator($logSeparator)
120 $this->logSeparator
= (string) $logSeparator;
125 * Get log separator string
129 public function getLogSeparator()
131 return $this->logSeparator
;
135 * Close the stream resource.
139 public function shutdown()
141 if (is_resource($this->stream
)) {
142 fclose($this->stream
);