padosoft/laravel-querymonitor

You can install the package via Composer:
composer require padosoft/laravel-querymonitor
Publish the configuration and migrations:
php artisan vendor:publish --provider="Padosoft\QueryMonitor\QueryMonitorServiceProvider" --tag="config"
The package configuration file is located at config/querymonitor.php. You can adjust the settings to suit your application's needs:
return [
'query' => [
'attiva' => env('QUERYMONITOR_QUERY_ATTIVA', true),
'maxExecutionTime' => env('QUERYMONITOR_QUERY_MAX_EXECUTION_TIME', 100), // in milliseconds
'sqlRegEx' => env('QUERYMONITOR_QUERY_SQL_REGEX', '^SELECT.*$'),
],
'query_builder' => [
'attiva' => env('QUERYMONITOR_BUILDER_ATTIVA', true),
'maxExecutionTime' => env('QUERYMONITOR_BUILDER_MAX_EXECUTION_TIME', 200), // in milliseconds
'methodRegEx' => env('QUERYMONITOR_BUILDER_METHOD_REGEX', '^(get|first)$'),
],
'total_queries' => [
/*
* Whether to enable total query monitoring.
*/
'attiva' => env('QUERYMONITOR_TOTAL_QUERIES_ATTIVA', true),
/*
* Maximum allowed total queries per request/command.
* If this threshold is exceeded, a warning is logged.
*/
'maxTotalQueries' => env('QUERYMONITOR_MAX_TOTAL_QUERIES', 500),
/*
* A regex to filter which contexts to monitor.
* - For HTTP requests, this regex will be matched against the full URL (including query string).
* - For Artisan commands, it will be matched against the command name.
* - For CLI contexts, it can be matched against the script name.
* If unset or empty, all contexts are monitored.
* Example: '^/api/.*$' to monitor only requests under /api/
*/
'traceRegEx' => env('QUERYMONITOR_TOTAL_QUERIES_REGEX', null),
],
];
Once installed and configured, the package will automatically monitor and log SQL queries and Eloquent methods based on the provided settings. If you setting query total count to true, the package will automatically monitor and log total queries count.
Example Log Entry:
[2024-11-28 12:34:56] local.INFO: QueryMonitor Slow SQL query detected {"query":"SELECT * FROM `users` WHERE `id` = '1'","execution_time":"150 ms"}
Example Log Entry:
{
"method": "get",
"execution_time": "250 ms",
"query": "SELECT * FROM `articles` WHERE `status` = 'published'",
"arguments": [
["*"]
],
"stack_trace": [
{
"file": "/path/to/your/project/app/Models/QueryBase.php",
"line": 123,
"class": "App\\Models\\QueryBase",
"function": "getPublishedArticles"
},
{
"file": "/path/to/your/project/app/Http/Controllers/ArticleController.php",
"line": 45,
"class": "App\\Http\\Controllers\\ArticleController",
"function": "index"
},
// ... additional frames up to the maximum stack depth
]
}
SQL Queries
Eloquent Methods
Why Both?
Suppose we have the following code:
$users = User::all();
Analysis:
In addition to monitoring slow queries and slow Eloquent methods, laravel-querymonitor allows you to track the total number of SQL queries executed during a single HTTP request, Artisan command, or CLI execution. This helps you identify cases where, although each individual query may be performant, the total number of queries is excessively high, potentially causing performance bottlenecks.
Why Monitor Total Queries? Even if every single query is fast, executing too many queries per request or command can cause unnecessary overhead. By monitoring the total query count, you can quickly identify scenarios where your application issues an excessive number of queries (for example, 2,000 queries in a single request), pinpointing areas that need optimization (e.g., using eager loading, caching, or refining data retrieval logic).
How It Works
All configuration options are defined in the querymonitor.php config file under the total_queries key:
'total_queries' => [
/*
* Whether to enable total query monitoring.
*/
'attiva' => env('QUERYMONITOR_TOTAL_QUERIES_ATTIVA', true),
/*
* Maximum allowed total queries per request/command.
* If this threshold is exceeded, a warning is logged.
*/
'maxTotalQueries' => env('QUERYMONITOR_MAX_TOTAL_QUERIES', 500),
/*
* A regex to filter which contexts to monitor.
* - For HTTP requests, this regex will be matched against the full URL (including query string).
* - For Artisan commands, it will be matched against the command name.
* - For CLI contexts, it can be matched against the script name.
* If unset or empty, all contexts are monitored.
* Example: '^/api/.*$' to monitor only requests under /api/
*/
'traceRegEx' => env('QUERYMONITOR_TOTAL_QUERIES_REGEX', null),
],
To track the total number of queries for HTTP requests, the package provides a TrackTotalQueriesMiddleware.
This middleware must be added as the first middleware in the global middleware stack.
By doing so, it can:
How to add it:
In your app/Http/Kernel.php, ensure that \Padosoft\QueryMonitor\Middleware\TrackTotalQueriesMiddleware::class appears at the top of the $middleware array:
protected $middleware = [
\Padosoft\QueryMonitor\Middleware\TrackTotalQueriesMiddleware::class,
// ... other global middleware ...
];
By placing the TrackTotalQueriesMiddleware first, you guarantee comprehensive coverage of every query executed during the request lifecycle. Once the request is fully processed, the middleware checks the total query count and logs a warning if it exceeds the configured threshold.
If a request executes more than the allowed number of queries, a log entry is created after the response is generated:
[2024-12-09 10:23:45] local.WARNING: Exceeded maximum total queries: 2020 queries (max: 500). {"context":"request","url":"https://example.com/products?category=shoes","method":"GET"}
context: request
url: The full URL of the request, including query parameters.
method: The HTTP method (e.g., GET, POST).
2. Artisan Command Exceeding the Query Limit
If an Artisan command triggers more queries than allowed, a warning is logged once the command finishes:
[2024-12-09 10:25:10] local.WARNING: Exceeded maximum total queries: 1200 queries (max: 500). {"context":"command","command":"cache:clear","arguments":["artisan","cache:clear"]}
context: command
command: The Artisan command name.
arguments: The arguments passed to the command.
3. CLI Context Exceeding the Query Limit
For CLI contexts (non-Artisan commands), if you set up tracking manually and the query count is exceeded, you'll see a log like:
[2024-12-09 10:26:00] local.WARNING: Exceeded maximum total queries: 3000 queries (max: 500). {"context":"cli-service","script":"myscript.php","arguments":["--option","value"]}
Using the Regex Filter If you provide a traceRegEx:
For example, if you set:
'traceRegEx' => '^/api/.*$',
only requests matching /api/... URLs are monitored.
Summary By configuring and enabling total query monitoring, you gain deeper insights into your application's performance, identifying excessive query usage patterns that can be addressed to improve overall efficiency. This is especially useful in complex, large-scale projects where minor optimizations in query counts can lead to significant performance gains.
The package includes unit tests to ensure all components function correctly. Run tests using PHPUnit:
composer test
Please see CHANGELOG for more information what has changed recently.
composer test
Please see CONTRIBUTING for details.
If you discover any security related issues, please email instead of using the issue tracker.
Padosoft (https://www.padosoft.com) is a software house based in Florence, Italy. Specialized in E-commerce and web sites.
The MIT License (MIT). Please see License File for more information.
How can I help you explore Laravel packages today?