Skip to content
Open
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
16 changes: 14 additions & 2 deletions src/Monolog/LogsHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -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']
);
}
}
23 changes: 23 additions & 0 deletions tests/Monolog/LogsHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down