| 1 |
<?php |
| 2 |
|
| 3 |
/* |
| 4 |
* This file is part of the Monolog package. |
| 5 |
* |
| 6 |
* (c) Jordi Boggiano <j.boggiano@seld.be> |
| 7 |
* |
| 8 |
* For the full copyright and license information, please view the LICENSE |
| 9 |
* file that was distributed with this source code. |
| 10 |
*/ |
| 11 |
|
| 12 |
/** |
| 13 |
* Stores to any stream resource |
| 14 |
* |
| 15 |
* Can be used to store into php://stderr, remote and local files, etc. |
| 16 |
* |
| 17 |
* @author Jordi Boggiano <j.boggiano@seld.be> |
| 18 |
*/ |
| 19 |
class Monolog_Handler_StreamHandler extends Monolog_Handler_AbstractProcessingHandler |
| 20 |
{ |
| 21 |
protected $stream; |
| 22 |
protected $url; |
| 23 |
private $errorMessage; |
| 24 |
|
| 25 |
/** |
| 26 |
* @param string $stream |
| 27 |
* @param integer $level The minimum logging level at which this handler will be triggered |
| 28 |
* @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not |
| 29 |
*/ |
| 30 |
public function __construct($stream, $level = Monolog_Logger::DEBUG, $bubble = true) |
| 31 |
{ |
| 32 |
parent::__construct($level, $bubble); |
| 33 |
if (is_resource($stream)) { |
| 34 |
$this->stream = $stream; |
| 35 |
} else { |
| 36 |
$this->url = $stream; |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* {@inheritdoc} |
| 42 |
*/ |
| 43 |
public function close() |
| 44 |
{ |
| 45 |
if (is_resource($this->stream)) { |
| 46 |
fclose($this->stream); |
| 47 |
} |
| 48 |
$this->stream = null; |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* {@inheritdoc} |
| 53 |
*/ |
| 54 |
protected function write(array $record) |
| 55 |
{ |
| 56 |
if (null === $this->stream) { |
| 57 |
if (!$this->url) { |
| 58 |
throw new LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().'); |
| 59 |
} |
| 60 |
$this->errorMessage = null; |
| 61 |
set_error_handler(array($this, 'customErrorHandler')); |
| 62 |
$this->stream = fopen($this->url, 'a'); |
| 63 |
restore_error_handler(); |
| 64 |
if (!is_resource($this->stream)) { |
| 65 |
$this->stream = null; |
| 66 |
throw new UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: '.$this->errorMessage, $this->url)); |
| 67 |
} |
| 68 |
} |
| 69 |
fwrite($this->stream, (string) $record['formatted']); |
| 70 |
} |
| 71 |
|
| 72 |
private function customErrorHandler($code, $msg) |
| 73 |
{ |
| 74 |
$this->errorMessage = preg_replace('{^fopen\(.*?\): }', '', $msg); |
| 75 |
} |
| 76 |
} |
| 77 |
|