diff --git a/doc/01-usage.md b/doc/01-usage.md index 75bc4023..8e2551f3 100644 --- a/doc/01-usage.md +++ b/doc/01-usage.md @@ -189,6 +189,9 @@ $logger->pushHandler($firephp); $securityLogger = new Logger('security'); $securityLogger->pushHandler($stream); $securityLogger->pushHandler($firephp); + +// Or clone the first one to only change the channel +$securityLogger = $logger->withName('security'); ``` ## Customizing the log format diff --git a/src/Monolog/Logger.php b/src/Monolog/Logger.php index 5ac72104..2fbc02c7 100644 --- a/src/Monolog/Logger.php +++ b/src/Monolog/Logger.php @@ -153,6 +153,19 @@ class Logger implements LoggerInterface return $this->name; } + /** + * Return a new cloned instance with the name changed + * + * @return static + */ + public function withName($name) + { + $new = clone $this; + $new->name = $name; + + return $new; + } + /** * Pushes a handler on to the stack. * diff --git a/tests/Monolog/LoggerTest.php b/tests/Monolog/LoggerTest.php index fee98040..c0bd1da9 100644 --- a/tests/Monolog/LoggerTest.php +++ b/tests/Monolog/LoggerTest.php @@ -33,6 +33,19 @@ class LoggerTest extends \PHPUnit_Framework_TestCase $this->assertEquals('ERROR', Logger::getLevelName(Logger::ERROR)); } + /** + * @covers Monolog\Logger::withName + */ + public function testWithName() + { + $first = new Logger('first', array($handler = new TestHandler())); + $second = $first->withName('second'); + + $this->assertSame('first', $first->getName()); + $this->assertSame('second', $second->getName()); + $this->assertSame($handler, $second->popHandler()); + } + /** * @covers Monolog\Logger::toMonologLevel */