Create log file while running artisan command directly in Laravel

Viewed 1297

I have this Command in the Kernel class :

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
    $schedule->command('products:import')
        ->appendOutputTo(storage_path('logs/import.log'));
}

The method creates a file named import.log that contains the logging that I added while importing the products, and it works fine. But I need to be able to just run php artisan products:import directly and get the file created too without calling the schedule method in the Kernel class, or using php artisan schedule:run.

I didn't find in the docs either. What should I add to php artisan products:import to get the file created?.

EDIT : if I run php artisan schedule:run, the log file gets created because of the appendOutputTo(storage_path('logs/import.log'));, but if I run php artisan products:import directly, the log file isn't created. I need to know what should I add to the php artisan products:import command line to make it work in this case too.

1 Answers

Override run method for your command and configure the $output stream to use a StreamOutput instead of a ConsoleOutput.

use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Illuminate\Console\Command;

class ImportCommand extends Command 
{ 
    function run(InputInterface $input=null, OutputInterface $output=null) {
        $output = new StreamOutput(fopen(storage_path('logs/import.log'), 'a', false));
        parent::run($input, $output);
    }
    
    function handle() {
         echo "Do stuff";
    }
}
Related