Skip to content

Instantly share code, notes, and snippets.

@zabaala
Last active March 2, 2021 07:50
Show Gist options
  • Star 56 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save zabaala/d1ba7986130474720b9487410dc73263 to your computer and use it in GitHub Desktop.
Save zabaala/d1ba7986130474720b9487410dc73263 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
@meneguite
Copy link

Muito bacana mano.. uso algo parecido aqui, só com uma abordagem levemente diferente usando variáveis de ambiente.. mas curti sua abordagem.. parabéns!!

@zabaala
Copy link
Author

zabaala commented Jun 19, 2018

Obrigado, @meneguite.

Como funciona o que você implementou? Compartilha ai.

Abraço.

@meneguite
Copy link

meneguite commented Jun 19, 2018

@zabaala aqui eu registro em um provider assim:
https://gist.github.com/meneguite/64e1622548e8d538aa65ed3072a7d745

Assim eu chaveio por uma variável de ambiente quando devo logar as queries.

@zabaala
Copy link
Author

zabaala commented Jun 20, 2018

Ahhh! massa, @meneguite.

Mas assim vc precisa dar um clear na config quando precisar modificar a variavel de ambiente, né?

@meneguite
Copy link

@zabaala normalmente eu uso isso só em desenvolvimento.. para validar algo.. mas sim, se fosse usar em produção.. eu teria que dar cache clear para pegar essa troca de parâmetros.. mas qualquer deploy novo no meu ambiente já faz esse processo.. logo para o meu caso isso não é um problema.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment