Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel PHP - Prepend Timestamp to Artisan Console Output

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

like image 516
Aaron Avatar asked Oct 09 '15 19:10

Aaron


2 Answers

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:

enter image description here

like image 146
peterm Avatar answered Sep 20 '22 22:09

peterm


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:

enter image description here

like image 38
Zohaib Avatar answered Sep 21 '22 22:09

Zohaib