Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Share logging context across channels and stacks #42276

Merged
merged 3 commits into from
May 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 49 additions & 3 deletions src/Illuminate/Log/LogManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ class LogManager implements LoggerInterface
*/
protected $dateFormat = 'Y-m-d H:i:s';

/**
* The context shared across channels and stacks.
*
* @var array
*/
protected $sharedContext = [];

/**
* Create a new Log manager instance.
*
Expand Down Expand Up @@ -84,10 +91,10 @@ public function build(array $config)
*/
public function stack(array $channels, $channel = null)
{
return new Logger(
return (new Logger(
$this->createStackDriver(compact('channels', 'channel')),
$this->app['events']
);
))->withContext($this->sharedContext);
}

/**
Expand Down Expand Up @@ -123,7 +130,7 @@ protected function get($name, ?array $config = null)
{
try {
return $this->channels[$name] ?? with($this->resolve($name, $config), function ($logger) use ($name) {
return $this->channels[$name] = $this->tap($name, new Logger($logger, $this->app['events']));
return $this->channels[$name] = $this->tap($name, new Logger($logger, $this->app['events']))->withContext($this->sharedContext);
});
} catch (Throwable $e) {
return tap($this->createEmergencyLogger(), function ($logger) use ($e) {
Expand Down Expand Up @@ -438,6 +445,45 @@ protected function formatter()
});
}

/**
* Share context across channels and stacks.
*
* @param array $context
* @return $this
*/
public function shareContext(array $context)
{
foreach ($this->channels as $channel) {
$channel->withContext($context);
}

$this->sharedContext = array_merge($this->sharedContext, $context);

return $this;
}

/**
* The context shared across channels and stacks.
*
* @return array
*/
public function sharedContext()
{
return $this->sharedContext;
}

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

return $this;
}

/**
* Get fallback log channel name.
*
Expand Down
2 changes: 2 additions & 0 deletions src/Illuminate/Support/Facades/Log.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
* @method static \Psr\Log\LoggerInterface build(array $config)
* @method static \Illuminate\Log\Logger withContext(array $context = [])
* @method static \Illuminate\Log\Logger withoutContext()
* @method static \Illuminate\Log\LogManager shareContext(array $context)
* @method static array sharedContext()
* @method static void alert(string $message, array $context = [])
* @method static void critical(string $message, array $context = [])
* @method static void debug(string $message, array $context = [])
Expand Down
91 changes: 91 additions & 0 deletions tests/Log/LogManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -481,4 +481,95 @@ public function testWrappingHandlerInFingersCrossedWhenActionLevelIsUsed()
$this->assertInstanceOf(StreamHandler::class, $expectedStreamHandler);
$this->assertEquals(Monolog::DEBUG, $expectedStreamHandler->getLevel());
}

public function testItSharesContextWithAlreadyResolvedChannels()
{
$manager = new LogManager($this->app);
$channel = $manager->channel('single');
$context = null;

$channel->listen(function ($message) use (&$context) {
$context = $message->context;
});
$manager->shareContext([
'invocation-id' => 'expected-id',
]);
$channel->info('xxxx');

$this->assertSame(['invocation-id' => 'expected-id'], $context);
}

public function testItSharesContextWithFreshlyResolvedChannels()
{
$manager = new LogManager($this->app);
$context = null;

$manager->shareContext([
'invocation-id' => 'expected-id',
]);
$manager->channel('single')->listen(function ($message) use (&$context) {
$context = $message->context;
});
$manager->channel('single')->info('xxxx');

$this->assertSame(['invocation-id' => 'expected-id'], $context);
}

public function testContextCanBePublicallyAccessedByOtherLoggingSystems()
{
$manager = new LogManager($this->app);
$context = null;

$manager->shareContext([
'invocation-id' => 'expected-id',
]);

$this->assertSame($manager->sharedContext(), ['invocation-id' => 'expected-id']);
}

public function testItSharesContextWithStacksWhenTheyAreResolved()
{
$manager = new LogManager($this->app);
$context = null;

$manager->shareContext([
'invocation-id' => 'expected-id',
]);
$stack = $manager->stack(['single']);
$stack->listen(function ($message) use (&$context) {
$context = $message->context;
});
$stack->info('xxxx');

$this->assertSame(['invocation-id' => 'expected-id'], $context);
}

public function testItMergesSharedContextRatherThanReplacing()
{
$manager = new LogManager($this->app);
$context = null;

$manager->shareContext([
'invocation-id' => 'expected-id',
]);
$manager->shareContext([
'invocation-start' => 1651800456,
]);
$manager->channel('single')->listen(function ($message) use (&$context) {
$context = $message->context;
});
$manager->channel('single')->info('xxxx', [
'logged' => 'context',
]);

$this->assertSame([
'invocation-id' => 'expected-id',
'invocation-start' => 1651800456,
'logged' => 'context',
], $context);
$this->assertSame([
'invocation-id' => 'expected-id',
'invocation-start' => 1651800456,
], $manager->sharedContext());
}
}