4

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?

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.