I am using the Laravel PHP framework.
What is the best way to prepend a timestamp to the Artisan console output (ie. $this->info, $this->error) for the App\Console\Command class?
I don't want to have to repeat a timestamp method in each and every line. I'd rather have it be automatic.
Thanks
One way to do it (assuming you're on Laravel 5.0+):
PrependsOutput.php
<?php 
namespace App\Console\Commands;
trait PrependsOutput
{
    public function line($string)
    {
        parent::line($this->prepend($string));
    }
    public function comment($string)
    {
        parent::comment($this->prepend($string));
    }
    public function error($string)
    {
        parent::error($this->prepend($string));
    }
    public function info($string)
    {
        parent::info($this->prepend($string));
    }
    public function warn($string)
    {
        parent::warn($this->prepend($string));
    }
    protected function prepend($string)
    {
        if (method_exists($this, 'getPrependString')) {
            return $this->getPrependString($string).$string;
        }
        return $string;
    }
}
PrependsTimestamp.php
<?php
namespace App\Console\Commands;
trait PrependsTimestamp
{
    protected function getPrependString($string)
    {
        return date(property_exists($this, 'outputTimestampFormat') ?
            $this->outputTimestampFormat : '[Y-m-d H:i:s]').' ';
    }
}
Then in your command:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class MyCommand extends Command
{
    use PrependsOutput, PrependsTimestamp;
    protected $signature = 'mycommand';
    protected $description = '';
    // you can override the default format
    // protected $outputTimestampFormat = '(m/d/Y H:i:s)';
    public function handle()
    {
        $this->comment('comment');
        $this->info('info');
        $this->warn('warn');
        $this->error('error');
        $this->line('line');
    }
}
Outcome:

From laravel 5.5 you can just add this trait.
and use it in your Console Commands
namespace App\Console;
trait PrependsTimestamp
{
    public function line($string, $style = null, $verbosity = null)
    {
        $timestamped = date('[Y-m-d H:i:s] ') . ucfirst($style) . ': ' . $string;
        $styled = $style ? "<$style>$timestamped</$style>" : $timestamped;
        $this->output->writeln($styled, $this->parseVerbosity($verbosity));
    }
}
Same Output:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With