padosoft/laravel-querymonitor
Installation:
composer require padosoft/laravel-querymonitor
Publish the config file:
php artisan vendor:publish --provider="Padosoft\QueryMonitor\QueryMonitorServiceProvider" --tag="config"
Enable Monitoring:
Add the middleware to your app/Http/Kernel.php under $middlewareGroups['web'] or $middlewareGroups['api']:
\Padosoft\QueryMonitor\Middleware\MonitorQueries::class,
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"
}
Monitoring HTTP Requests:
Artisan Commands:
MonitorQueries middleware or manually trigger monitoring:
use Padosoft\QueryMonitor\Facades\QueryMonitor;
QueryMonitor::startMonitoring();
// Your slow command logic here
QueryMonitor::stopMonitoring();
Custom Thresholds:
config/querymonitor.php:
'slow_query_threshold' => 500, // milliseconds
'slow_eloquent_threshold' => 1000, // milliseconds
Logging to External Services:
QueryMonitor::setLogger(function ($data) {
// Send $data to your external service
});
Monitoring Specific Eloquent Methods:
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;
}
}
Query Count Tracking:
$totalQueries = QueryMonitor::getTotalQueries();
Performance Overhead:
'enabled' => env('APP_ENV') !== 'production',
Middleware Placement:
MonitorQueries after StartSession and Authenticate to avoid logging queries from middleware itself.$except in the middleware.Eloquent Method Nesting:
startMonitoringEloquent()/stopMonitoringEloquent() calls, as it may lead to incorrect timing logs.Raw Query Logging:
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();
Log Rotation:
storage/logs/ has sufficient disk space, as slow queries may generate large log files.Verify Middleware:
Kernel.php and not overridden by other packages.Check Config:
config/querymonitor.php for correct thresholds and enabled/disabled settings.Log Levels:
debug to ensure slow queries are captured:
'level' => 'debug',
Test Locally:
DB::connection()->getPdo()->exec("SET GLOBAL slow_query_log=1"); (MySQL) or equivalent for your DB.Extension Points:
QueryMonitorLogger interface:
$this->app->bind(\Padosoft\QueryMonitor\Contracts\QueryMonitorLogger::class, function () {
return new CustomLogger();
});
Exclude Queries:
'exclude_queries' => function ($query) {
return str_contains($query, 'cache:');
},
Artisan Commands:
QueryMonitor::startMonitoring();
// Your CLI logic
QueryMonitor::dumpResults(); // Manually dump to log
How can I help you explore Laravel packages today?