Skip to content

Instantly share code, notes, and snippets.

@carestad
Created August 18, 2021 11:28
Show Gist options
  • Save carestad/4c3d1930a9823d9114bd2a0207711a78 to your computer and use it in GitHub Desktop.
Save carestad/4c3d1930a9823d9114bd2a0207711a78 to your computer and use it in GitHub Desktop.
Laravel console command log trait. This adds a few logXX() methods which will append a timestamp in front of the logged text + take verbosity level into account so -vvv can log more than -v
<?php
namespace App\Console\Commands\Traits;
trait LogTrait
{
public function logDebug(string $text, ?string $dateFormat = 'Y-m-d H:i:s'): void
{
/** @var \Illuminate\Console\Command $this */
if (! $this->output->isDebug()) {
return;
}
// If $dateformat is NULL it is disabled
if ($dateFormat) {
$date = date($dateFormat);
$text = "[{$date}]: {$text}";
}
$this->warn($text);
}
public function logInfo(string $text, ?string $dateFormat = 'Y-m-d H:i:s'): void
{
/** @var \Illuminate\Console\Command $this */
if (! $this->output->isVerbose()) {
return;
}
// If $dateformat is NULL it is disabled
if ($dateFormat) {
$date = date($dateFormat);
$text = "[{$date}]: {$text}";
}
$this->info($text);
}
public function logWarn(string $text, ?string $dateFormat = 'Y-m-d H:i:s'): void
{
/** @var \Illuminate\Console\Command $this */
if ($this->output->isQuiet()) {
return;
}
// If $dateformat is NULL it is disabled
if ($dateFormat) {
$date = date($dateFormat);
$text = "[{$date}]: {$text}";
}
$this->warn($text);
}
public function logError(string $text, ?string $dateFormat = 'Y-m-d H:i:s'): void
{
/** @var \Illuminate\Console\Command $this */
// If $dateformat is NULL it is disabled
if ($dateFormat) {
$date = date($dateFormat);
$text = "[{$date}]: {$text}";
}
$this->error($text);
}
public function logVerbose(string $text, ?string $dateFormat = 'Y-m-d H:i:s'): void
{
/** @var \Illuminate\Console\Command $this */
if (! $this->output->isVerbose()) {
return;
}
// If $dateformat is NULL it is disabled
if ($dateFormat) {
$date = date($dateFormat);
$text = "[{$date}]: {$text}";
}
$this->info($text);
}
public function logVeryVerbose(string $text, ?string $dateFormat = 'Y-m-d H:i:s'): void
{
/** @var \Illuminate\Console\Command $this */
if (! $this->output->isVeryVerbose()) {
return;
}
// If $dateformat is NULL it is disabled
if ($dateFormat) {
$date = date($dateFormat);
$text = "[{$date}]: {$text}";
}
$this->info($text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment