Installation:
composer require dziki/monolog-sentry-bundle
Add to config/bundles.php:
return [
// ...
Dziki\MonologSentryBundle\DzikiMonologSentryBundle::class => ['all' => true],
];
Configure Sentry:
Add Sentry client configuration to config/packages/dev/monolog.yaml (or your environment):
monolog:
handlers:
sentry:
type: sentry
dsn: "%env(SENTRY_DSN)%"
level: !php/const Monolog\Logger::ERROR
bubble: false
channels: ["!doctrine", "!console"]
with_locals: true
with_extra: true
First Use Case: Log an error with enriched context:
$this->logger->error('Failed to process payment', [
'user_id' => $user->id,
'amount' => $amount,
]);
The bundle auto-attaches:
Request or User context)Context Injection:
user, ip, user_agent, and referer from the Symfony Request stack.security.token_storage to fetch the current user (must implement Serializable or have a getId() method).Dziki\MonologSentryBundle\Processor\UserContextProcessor to inject additional data:
public function __invoke(array $record): array {
$record['extra']['custom_data'] = $this->getCustomData();
return $record;
}
Tagging Strategy:
config/packages/monolog.yaml:
monolog:
processors:
dziki.sentry.tags: ['env:production', 'app:myapp']
$this->logger->critical('Database down', [], ['tag' => 'db']);
Environment-Specific Logging:
dev:
# config/packages/dev/monolog.yaml
monolog:
handlers:
sentry:
level: !php/const Monolog\Logger::OFF
Integration with Monolog Channels:
api.errors):
monolog:
channels:
- { name: api.errors, type: channel }
handlers:
sentry:
channels: ["api.errors"]
Git Metadata:
Enable Git revision logging by adding to config/packages/monolog.yaml:
monolog:
processors:
dziki.sentry.git: true
Requires git CLI installed on the server.
Custom Processors: Create a service to extend context:
// src/Service/CustomSentryContext.php
class CustomSentryContext implements ProcessorInterface {
public function __invoke(array $record): array {
$record['extra']['feature_flag'] = $this->featureFlagService->isEnabled('new_ui');
return $record;
}
}
Register in config/services.yaml:
services:
App\Service\CustomSentryContext:
tags: ['monolog.processor']
User Context Missing:
$user is not attached, the bundle silently skips user-related fields. Ensure your User entity implements Serializable or has a getId() method.$this->logger->debug('User context', ['user' => $this->get('security.token_storage')->getToken()?->getUser()]);
Performance Overhead:
config/packages/monolog.yaml:
monolog:
processors:
dziki.sentry.user: false # Disable if not needed
dziki.sentry.git: false # Disable if not in Git repo
DSN Exposure:
SENTRY_DSN is never committed to version control. Use .env and .env.local:
echo "SENTRY_DSN=your_dsn" >> .env.local
git add .env.local # Oops! Undo with `git rm --cached .env.local`
Symfony Version Mismatch:
UserContextProcessor if TokenStorage changes break it.Log the Raw Record:
Add a stream handler temporarily to inspect processed logs:
monolog:
handlers:
stream:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
Check for missing fields like extra.user or extra.git.
Disable Processors Individually: Isolate which processor is causing issues:
monolog:
processors:
dziki.sentry.user: false
dziki.sentry.git: false
dziki.sentry.tags: false
Custom Fields: Override the processor to add fields like:
// src/Processor/CustomSentryProcessor.php
class CustomSentryProcessor extends AbstractProcessor {
public function __invoke(array $record): array {
$record['extra']['locale'] = $this->requestStack->getCurrentRequest()->getLocale();
return parent::__invoke($record);
}
}
Register as a Monolog processor:
services:
App\Processor\CustomSentryProcessor:
tags: ['monolog.processor']
arguments:
$requestStack: '@request_stack'
Conditional Logging: Skip Sentry for specific logs:
if (!$this->isProduction()) {
$this->logger->error('Test error', [], ['skip_sentry' => true]);
}
Add a custom processor to filter:
public function __invoke(array $record): array {
if (isset($record['extra']['skip_sentry'])) {
$record['level'] = Monolog\Logger::WARNING; // Downgrade to avoid Sentry
}
return $record;
}
Breadcrumbs: Manually add breadcrumbs for critical paths:
$this->logger->info('User clicked "Submit"', [
'level' => 'breadcrumb',
'category' => 'ui',
'data' => ['button' => 'submit']
]);
Ensure your Sentry client supports breadcrumbs (most modern SDKs do).
Processor Order:
Processors run in the order defined in config/packages/monolog.yaml. Place dziki.sentry.* after your custom processors to override their data.
RequestStack Dependency:
The bundle requires request_stack to be available. For CLI commands, mock the request:
$request = Request::create('/cli');
$this->container->get('request_stack')->push($request);
Git Metadata:
If git CLI is unavailable, the bundle falls back to git describe --always --dirty. Ensure the repo is initialized and the user has permissions.
How can I help you explore Laravel packages today?