2015-10-09 56 views
0

我正在使用Laravel PHP框架。Laravel PHP - 在工匠控制台输出上添加时间戳

什么是为App\Console\Command类添加Artisan控制台输出(即$this->info$this->error)的时间戳的最佳方法是什么?

我不想在每一行都重复一次timestamp方法。我宁愿它是自动的。

感谢

回答

6

一种方式做到这一点(假设你是在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]').' '; 
    } 
} 

然后在你的命令中:

<?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'); 
    } 
} 

结果:

enter image description here

+0

大,谢谢! – Aaron

+0

不确定它是否是Laravel 5.5的东西,但是现在只需要重写'line()'方法并负责所有输出方法。 – Aaron