I would like to log laravel queries. I know that we can listen to laravel queries using the following code:
Event::listen('illuminate.query', function ($query, $bindings, $time, $name) {
// Log queries
};
I would like to place above code in an artisan command so that I only listen to queries when this program is running, and not all the time. I wrote the following code.
<?php
// ... namespace and use statements
class QueryListener extends Command
{
protected $signature = 'pots:query-listen';
protected $description = 'Runs forever and logs all database queries.';
public function __construct()
{
parent::__construct();
}
private function logDatabaseQueries()
{
Event::listen('illuminate.query', function ($query, $bindings, $time, $name) {
Log::info(PHP_EOL.$query.PHP_EOL);
});
}
public function handle()
{
$this->logDatabaseQueries();
echo 'Listening for database queries: Type \'stop\' to stop execution.'.PHP_EOL;
$stopExecution = false;
while ($stopExecution === false) {
$handle = fopen('php://stdin', 'r');
$line = fgets($handle);
if (strtolower(trim($line)) === 'stop') {
fclose($handle);
echo 'Aborting script.'.PHP_EOL;
$stopExecution = true;
}
}
}
}
My expectation was that as soon as I run this command using artisan
, the logDatabaseQueries()
method will start listening for events. However this is not working because I never receive any query events. Am I thinking in the right direction?