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

Laravel Querymonitor Laravel Package

padosoft/laravel-querymonitor

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require padosoft/laravel-querymonitor
    

    Publish the config file:

    php artisan vendor:publish --provider="Padosoft\QueryMonitor\QueryMonitorServiceProvider" --tag="config"
    
  2. Enable Monitoring: Add the middleware to your app/Http/Kernel.php under $middlewareGroups['web'] or $middlewareGroups['api']:

    \Padosoft\QueryMonitor\Middleware\MonitorQueries::class,
    
  3. First Use Case: Trigger a slow query in your application (e.g., a complex join or where clause) and check the logs (storage/logs/laravel.log by default) for entries like:

    {
        "query": "SELECT * FROM users WHERE ...",
        "time": 1200.5, // in milliseconds
        "type": "slow_query"
    }
    

Implementation Patterns

Core Workflows

  1. Monitoring HTTP Requests:

    • Automatically logs slow queries and Eloquent method execution times for every request due to the middleware.
    • Example: Useful for identifying bottlenecks in API endpoints or admin dashboards.
  2. Artisan Commands:

    • Wrap slow commands with the MonitorQueries middleware or manually trigger monitoring:
      use Padosoft\QueryMonitor\Facades\QueryMonitor;
      
      QueryMonitor::startMonitoring();
      // Your slow command logic here
      QueryMonitor::stopMonitoring();
      
  3. Custom Thresholds:

    • Configure thresholds in config/querymonitor.php:
      'slow_query_threshold' => 500, // milliseconds
      'slow_eloquent_threshold' => 1000, // milliseconds
      
  4. Logging to External Services:

    • Extend the logger to send data to tools like Datadog, Sentry, or custom APIs:
      QueryMonitor::setLogger(function ($data) {
          // Send $data to your external service
      });
      
  5. Monitoring Specific Eloquent Methods:

    • Decorate Eloquent models to track method execution:
      use Padosoft\QueryMonitor\Facades\QueryMonitor;
      
      class User extends Model {
          public function findByEmail($email) {
              QueryMonitor::startMonitoringEloquent('User::findByEmail');
              $user = self::where('email', $email)->first();
              QueryMonitor::stopMonitoringEloquent();
              return $user;
          }
      }
      
  6. Query Count Tracking:

    • Access the total query count for a request via:
      $totalQueries = QueryMonitor::getTotalQueries();
      

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Monitoring adds minimal overhead (~1-5ms per query), but avoid enabling it in production for high-traffic endpoints unless necessary.
    • Disable in production via config:
      'enabled' => env('APP_ENV') !== 'production',
      
  2. Middleware Placement:

    • Place MonitorQueries after StartSession and Authenticate to avoid logging queries from middleware itself.
    • Exclude specific routes by adding them to $except in the middleware.
  3. Eloquent Method Nesting:

    • Avoid nesting startMonitoringEloquent()/stopMonitoringEloquent() calls, as it may lead to incorrect timing logs.
    • Use a context manager or decorator pattern for complex methods.
  4. Raw Query Logging:

    • Raw queries (e.g., DB::select()) are logged, but parameter binding may not be visible. Use toSql() for debugging:
      $sql = DB::select('SELECT * FROM users WHERE id = ?', [$id])->toSql();
      
  5. Log Rotation:

    • Ensure storage/logs/ has sufficient disk space, as slow queries may generate large log files.

Debugging Tips

  1. Verify Middleware:

    • Check if the middleware is registered in Kernel.php and not overridden by other packages.
  2. Check Config:

    • Validate config/querymonitor.php for correct thresholds and enabled/disabled settings.
  3. Log Levels:

    • Adjust Laravel's log level to debug to ensure slow queries are captured:
      'level' => 'debug',
      
  4. Test Locally:

    • Simulate slow queries with DB::connection()->getPdo()->exec("SET GLOBAL slow_query_log=1"); (MySQL) or equivalent for your DB.
  5. Extension Points:

    • Override the default logger by binding a custom QueryMonitorLogger interface:
      $this->app->bind(\Padosoft\QueryMonitor\Contracts\QueryMonitorLogger::class, function () {
          return new CustomLogger();
      });
      
  6. Exclude Queries:

    • Skip monitoring for specific queries using a callback in config:
      'exclude_queries' => function ($query) {
          return str_contains($query, 'cache:');
      },
      
  7. Artisan Commands:

    • For CLI scripts, manually wrap monitoring blocks to avoid middleware interference:
      QueryMonitor::startMonitoring();
      // Your CLI logic
      QueryMonitor::dumpResults(); // Manually dump to log
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle