Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Doctrine Dependency Logger Laravel Package

app-insights-php/doctrine-dependency-logger

Doctrine dependency logger for PHP that tracks and records Doctrine-related dependencies/events to help debug and understand runtime wiring. Useful for inspecting Doctrine configuration, service usage, and dependency resolution in apps using Doctrine ORM/DBAL.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require app-insights-php/doctrine-dependency-logger
    
  2. Register the Logger In your Laravel service provider (e.g., AppServiceProvider.php), bind the dependency logger to Doctrine’s event system:

    use AppInsights\DoctrineDependencyLogger\DoctrineDependencyLogger;
    use Doctrine\DBAL\Connection;
    
    public function register()
    {
        $this->app->bind(DoctrineDependencyLogger::class, function ($app) {
            $connection = $app->make(Connection::class);
            $logger = new DoctrineDependencyLogger($connection, $app['appinsights']);
            return $logger;
        });
    }
    
  3. First Use Case: Logging Queries Attach the logger to Doctrine’s event manager in your bootstrap/app.php or a service provider:

    $connection->getEventManager()->addEventListener(
        'connection.query',
        $this->app->make(DoctrineDependencyLogger::class)
    );
    

Implementation Patterns

Workflow: Query Telemetry

  1. Instrument Existing Queries Use the logger to automatically capture SQL queries, execution time, and parameters:

    $query = $connection->createQueryBuilder()
        ->select('*')
        ->from('users')
        ->where('id = :id')
        ->setParameter('id', 1)
        ->execute();
    

    The logger will emit telemetry to App Insights for this query.

  2. Custom Telemetry Attributes Extend the logger to add custom dimensions (e.g., user context):

    $logger->setCustomProperties(['user_id' => auth()->id()]);
    
  3. Conditional Logging Disable logging for specific queries or environments:

    if (app()->environment('production')) {
        $connection->getEventManager()->addEventListener(
            'connection.query',
            $this->app->make(DoctrineDependencyLogger::class)
        );
    }
    

Integration Tips

  • Laravel Eloquent: Use DB::connection()->getEventManager() to attach the logger to Eloquent queries.
  • Middleware: Log queries in middleware for API endpoints:
    public function handle($request, Closure $next)
    {
        $logger = app(DoctrineDependencyLogger::class);
        $logger->setCustomProperties(['endpoint' => $request->path()]);
        return $next($request);
    }
    
  • Batch Logging: For bulk operations, use connection.query events to log aggregated metrics.

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Issue: Excessive logging can slow down queries.
    • Fix: Use conditional logging (e.g., only in staging/production) or sample queries:
      if (rand(0, 100) < 10) { // 10% sampling
          $logger->logQuery($event);
      }
      
  2. Missing Telemetry

    • Issue: Queries may not appear in App Insights if the logger isn’t attached to the event manager.
    • Fix: Verify the listener is registered:
      $connection->getEventManager()->addEventListener('connection.query', $logger);
      
  3. Parameter Masking

    • Issue: Sensitive data (e.g., passwords) may leak in query logs.
    • Fix: Override DoctrineDependencyLogger::getMaskedParams() to redact sensitive fields:
      protected function getMaskedParams(array $params): array
      {
          $params['password'] = '[REDACTED]';
          return $params;
      }
      

Debugging

  • Check Event Listeners: Ensure the logger is subscribed to connection.query:
    $listeners = $connection->getEventManager()->getListeners('connection.query');
    
  • App Insights Validation: Verify telemetry in the Azure Portal under Application Insights > Transactions > Dependencies.

Extension Points

  1. Custom Telemetry Extend the logger to emit additional metrics (e.g., query complexity):

    public function logQuery($event)
    {
        $this->telemetryClient->trackDependency(
            'DoctrineQuery',
            $event->getSql(),
            'SQL',
            DateInterval::fromMillis($event->getExecutionTime())
        );
        // Add custom logic here
    }
    
  2. Async Logging Offload logging to a queue for high-traffic apps:

    public function logQuery($event)
    {
        QueryLogJob::dispatch($event->getSql(), $event->getExecutionTime());
    }
    
  3. Environment-Specific Config Use Laravel’s config to toggle logging:

    'app_insights' => [
        'doctrine_logging' => env('APP_INSIGHTS_DOCTRINE_LOGGING', false),
    ],
    

    Then conditionally attach the logger:

    if (config('app_insights.doctrine_logging')) {
        $connection->getEventManager()->addEventListener('connection.query', $logger);
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui