Search code examples
phplaravellaravel-artisan

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


Solution

  • 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