Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidis405/dc59393b19f9e67ed3e4d7f7d3800187 to your computer and use it in GitHub Desktop.
Save sidis405/dc59393b19f9e67ed3e4d7f7d3800187 to your computer and use it in GitHub Desktop.
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