Skip to content

Commit

Permalink
[8.x] Add context to subsequent logs. (#37847)
Browse files Browse the repository at this point in the history
* Add context to future logs.
- Update Logger.php to store context in state
- Add test to ensure it works properly

* formatting

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
chasenyc and taylorotwell authored Jun 28, 2021
1 parent e89ab5a commit b0ae212
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
37 changes: 36 additions & 1 deletion src/Illuminate/Log/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -171,11 +178,39 @@ public function write($level, $message, array $context = [])
*/
protected function writeLog($level, $message, $context)
{
$this->logger->{$level}($message = $this->formatMessage($message), $context);
$this->logger->{$level}(
$message = $this->formatMessage($message),
$context = array_merge($this->context, $context)
);

$this->fireLogEvent($level, $message, $context);
}

/**
* Add context to all future logs.
*
* @param array $context
* @return $this
*/
public function withContext(array $context = [])
{
$this->context = array_merge($this->context, $context);

return $this;
}

/**
* Flush the existing context array.
*
* @return $this
*/
public function withoutContext()
{
$this->context = [];

return $this;
}

/**
* Register a new callback handler for when a log event is triggered.
*
Expand Down
10 changes: 10 additions & 0 deletions tests/Log/LogLoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ public function testMethodsPassErrorAdditionsToMonolog()
$writer->error('foo');
}

public function testContextIsAddedToAllSubsequentLogs()
{
$writer = new Logger($monolog = m::mock(Monolog::class));
$writer->withContext(['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);
Expand Down

0 comments on commit b0ae212

Please sign in to comment.