Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log Laravel with artisan output

Tags:

php

laravel

I'm working with Laravel and I trying to do a log of some function output with this Log function:

Log::warning("some message")

But if I want to write in console and log file I need to write two times the same message with different function like this:

Log::warning("some message") //This work good for log file

dump("some message") //This work good for artisan console output

There is some function that allow me only use one of both?

like image 721
Sergio Barbosa Avatar asked Mar 07 '23 03:03

Sergio Barbosa


1 Answers

You can use Laravel events to integrate this functionality without requiring any change to the way you currently log information.

Add a listener for the Illuminate\Log\Events\MessageLogged event, and within your listener output the log entry to the console if the request has come from the console -- using runningInConsole().

  1. Register a new listener called MessageLoggedListener, e.g:

    protected $listen = [
        'Illuminate\Log\Events\MessageLogged' => [
            'App\Listeners\MessageLoggedListener',
        ],
    ];
    
  2. Generate your listener with php artisan event:generate

  3. Add the event handler to your listener:

    /**
    * Handle the event.
    *
    * @param  MessageLogged  $event
    * @return void
    */
    public function handle(MessageLogged $event)
    {
        if (app()->runningInConsole()) {
            $output = new ConsoleOutput();
            $output->writeln("<error>{$event->message}</error>");
        }
    }
    

That's it! You're now ready to test the functionality. From a console command log a message, e.g:

    public function handle()
    {
        Log::error('Hello world! This is an error.');
    }

This is the output you'll see:

$ php artisan command
Hello world! This is an error.

And within your log file you'll see:

[2018-01-15 16:55:46] local.WARNING: Hello world! This is an error.

You can improve the functionality by adding different output styles, for example you may wish to use error for errors and info for info. You can read about styling your output here in the Symfony documentation.

like image 133
sam Avatar answered Mar 28 '23 06:03

sam