Created
October 1, 2013 17:57
-
-
Save ZhukV/6782416 to your computer and use it in GitHub Desktop.
Override monolog stream handler for auto create directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme\Demo\Monolog\Handler; | |
use Monolog\Handler\StreamHandler as BaseStreamHandler; | |
use Symfony\Component\Filesystem\Filesystem; | |
/** | |
* Auto create log directory, if directory not found. | |
* The base stream handler in monolog package not auto created | |
* directory. | |
*/ | |
class StreamHandler extends BaseStreamHandler | |
{ | |
const RIGHT = 0777; | |
/** | |
* {@inheritDoc} | |
*/ | |
public function write(array $record) | |
{ | |
if (null === $this->stream) { | |
if ($this->url) { | |
if (stream_is_local($this->url)) { | |
$dir = dirname($this->url); | |
$fileSystem = new Filesystem(); | |
if (!is_dir($dir)) { | |
$old = umask(0); | |
// Create directory | |
$fileSystem->mkdir($dir, self::RIGHT); | |
umask($old); | |
} | |
if (!is_file($this->url)) { | |
// Create empty file and change right | |
$fileSystem->touch($this->url); | |
$fileSystem->chmod($this->url, self::RIGHT); | |
} | |
} | |
} | |
} | |
parent::write($record); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme\Demo\Tests\Monolog\Handler; | |
use Acme\Demo\Monolog\Handler\StreamHandler; | |
class StreamHandlerTest extends \PHPUnit_Framework_TestCase | |
{ | |
/** | |
* Test with create directory and touch file | |
*/ | |
public function testBase() | |
{ | |
$dir = sys_get_temp_dir() . '/foo/bar/d' . time(); | |
$file = $dir . '/' . time() . '.log'; | |
$handler = new StreamHandler($file); | |
$handler->write(array( | |
'formatted' => 'First record' | |
)); | |
$this->assertTrue(is_dir($dir), sprintf('Directory "%s" not auto created.', $dir)); | |
$this->assertTrue(is_file($file), sprintf('File log "%s" not created.', $file)); | |
$logContent = file_get_contents($file); | |
$this->assertContains('First record', trim($logContent)); | |
@unlink($file); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment