diff --git a/src/Illuminate/Log/Logger.php b/src/Illuminate/Log/Logger.php index e5a8de6287f9..2f9969dd9a7c 100755 --- a/src/Illuminate/Log/Logger.php +++ b/src/Illuminate/Log/Logger.php @@ -26,6 +26,13 @@ class Logger implements LoggerInterface */ protected $dispatcher; + /** + * Any context to be added to logs. + * + * @var array + */ + protected $context = []; + /** * Create a new log writer instance. * @@ -161,6 +168,27 @@ public function write($level, $message, array $context = []) $this->writeLog($level, $message, $context); } + /** + * Adds context to all future logs. + * + * @param array $context + * @return void + */ + public function addContextToLogs($context = []) + { + $this->context = array_merge([], $this->context, $context); + } + + /** + * Clears any set context from future logs. + * + * @return void + */ + public function clearContext() + { + $this->context = []; + } + /** * Write a message to the log. * @@ -171,6 +199,8 @@ public function write($level, $message, array $context = []) */ protected function writeLog($level, $message, $context) { + $context = array_merge([], $this->context, $context); + $this->logger->{$level}($message = $this->formatMessage($message), $context); $this->fireLogEvent($level, $message, $context); diff --git a/tests/Log/LogLoggerTest.php b/tests/Log/LogLoggerTest.php index 208bf9e3b812..76fcb40e9a1a 100755 --- a/tests/Log/LogLoggerTest.php +++ b/tests/Log/LogLoggerTest.php @@ -26,6 +26,16 @@ public function testMethodsPassErrorAdditionsToMonolog() $writer->error('foo'); } + public function testContextIsAddedToAllSubsequentLogs() + { + $writer = new Logger($monolog = m::mock(Monolog::class)); + $writer->addContextToLogs(['bar' => 'baz']); + + $monolog->shouldReceive('error')->once()->with('foo', ['bar' => 'baz']); + + $writer->error('foo'); + } + public function testLoggerFiresEventsDispatcher() { $writer = new Logger($monolog = m::mock(Monolog::class), $events = new Dispatcher);