Skip to content

Commit

Permalink
Add context to future logs.
Browse files Browse the repository at this point in the history
- Update Logger.php to store context in state
- Add test to ensure it works properly
  • Loading branch information
chasenyc committed Jun 28, 2021
1 parent 3a8082e commit e438b71
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
30 changes: 30 additions & 0 deletions 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 @@ -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.
*
Expand All @@ -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);
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->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);
Expand Down

0 comments on commit e438b71

Please sign in to comment.