Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
php artisan db:log <start> <stop>
<?php
namespace App\Commands\Database;
use Illuminate\Support\ServiceProvider;
class BindDatabaseServiceProvider extends ServiceProvider
{
public function boot()
{
$file = storage_path('/logs/queries.log');
if (! file_exists($file)) {
return ;
}
\DB::listen(function ($query) use ($file) {
$data = $query->sql . "\n";
$data .= print_r($query->bindings, true);
$data .= "TIME: " . $query->time . "\n";
$data .= "----\n";
$data .= "\n";
file_put_contents($file, $data, FILE_APPEND);
});
}
}
<?php
namespace App\Commands\Database;
use Illuminate\Console\Command;
use Symfony\Component\Process\Process;
class LogCommand extends Command
{
/**
* @var null|string
*/
private $logFile = null;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'db:log
{--start : Start log}
{--stop : Stop log}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Log database queries.';
/**
* Create a new command instance.
* @param string $filename
*/
public function __construct($filename = 'queries.log')
{
parent::__construct();
$this->logFile = storage_path(sprintf("logs/%s", $filename));
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// starting log...
if ($this->option('start')) {
// create log file
exec("touch " . $this->logFile);
// run tail and send outputs to the user console.
(new Process("clear && tail -f " . escapeshellarg($this->logFile)))
->setTimeout(null)
->run(function ($type, $line) {
$this->output->write($line);
});
}
// stop...
if ($this->hasArgument('stop') && $this->logFileExists()) {
exec("rm " . $this->logFile);
}
}
/**
* @return bool
*/
private function logFileExists()
{
return file_exists($this->logFile);
}
}

Usage:

Start loging

This will create a queries.log file inside of storage/logs directory and tailing the file.

php artisan db:log --start

Stop loging

This will delete queries.log.

php artisan db:log --stop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.