diff --git a/src/Monolog/LogsHandler.php b/src/Monolog/LogsHandler.php index 17c67d88d..710fc2b48 100644 --- a/src/Monolog/LogsHandler.php +++ b/src/Monolog/LogsHandler.php @@ -29,16 +29,23 @@ class LogsHandler implements HandlerInterface */ private $bubble; + /** + * Whether to include the channel name as an attribute in the Sentry logs. + */ + private bool $includeChannel; + /** * Creates a new Monolog handler that converts Monolog logs to Sentry logs. * * @param LogLevel|\Monolog\Level|int|null $logLevel the minimum logging level at which this handler will be triggered and collects the logs * @param bool $bubble whether the messages that are handled can bubble up the stack or not + * @param bool $includeChannel whether to include the channel name as an attribute in the Sentry logs */ - public function __construct($logLevel = null, bool $bubble = true) + public function __construct($logLevel = null, bool $bubble = true, bool $includeChannel = false) { $this->logLevel = $logLevel ?? LogLevel::debug(); $this->bubble = $bubble; + $this->includeChannel = $includeChannel; } /** @@ -137,6 +144,11 @@ public function __destruct() */ protected function compileAttributes($record): array { - return array_merge($record['context'], $record['extra'], ['sentry.origin' => 'auto.log.monolog']); + return array_merge( + $this->includeChannel ? ['channel' => $record['channel']] : [], + $record['context'], + $record['extra'], + ['sentry.origin' => 'auto.log.monolog'] + ); } } diff --git a/tests/Monolog/LogsHandlerTest.php b/tests/Monolog/LogsHandlerTest.php index 004a80c38..3d0b356ff 100644 --- a/tests/Monolog/LogsHandlerTest.php +++ b/tests/Monolog/LogsHandlerTest.php @@ -135,6 +135,29 @@ public function testOriginTagAppliedWithHandler(): void $this->assertSame('auto.log.monolog', $log->attributes()->toSimpleArray()['sentry.origin']); } + public function testChannelNotIncludedByDefault(): void + { + $handler = new LogsHandler(); + $handler->handle(RecordFactory::create('without channel', Logger::WARNING, 'channel.foo', [], [])); + + $logs = Logs::getInstance()->aggregator()->all(); + $this->assertCount(1, $logs); + $log = $logs[0]; + $this->assertArrayNotHasKey('channel', $log->attributes()->toSimpleArray()); + } + + public function testChannelIncludedWhenEnabled(): void + { + $handler = new LogsHandler(LogLevel::warn(), true, true); + $handler->handle(RecordFactory::create('with channel', Logger::WARNING, 'channel.foo', [], [])); + + $logs = Logs::getInstance()->aggregator()->all(); + $this->assertCount(1, $logs); + $log = $logs[0]; + $this->assertArrayHasKey('channel', $log->attributes()->toSimpleArray()); + $this->assertSame('channel.foo', $log->attributes()->toSimpleArray()['channel']); + } + public function testOriginTagNotAppliedWhenUsingDirectly() { \Sentry\logger()->info('No origin attribute');