2

I'd like to log the user's name along with the error that is outputted to the log. How do I add a variable to the beginning of an error log entry that outputs an exception?

KingKongFrog
  • 13,946
  • 21
  • 75
  • 124
  • Do you want to do that for every error log or just the one? – fos.alex Oct 21 '15 at 20:48
  • Every log entry. That way I can identify who initiated the error. For example it says `[2015-10-17 08:33:54] development.ERROR: ` I'd like `[2015-10-17 08:33:54] development.ERROR [johndoe]:` – KingKongFrog Oct 21 '15 at 20:49

1 Answers1

2

I think I've got a fairly easy way to do this.

Solution 1

Create a new folder under app called handlers and create a new class called CustomStreamHandler.php which will hold the custom monolog handler.

namespace App\Handlers;

use Monolog\Handler\StreamHandler;
use Auth;

class CustomStreamHandler extends StreamHandler
{
    protected function write(array $record)
    {
        $record['context']['user'] = Auth::check() ? Auth::user()->name : 'guest';

        parent::write($record);
    }
}

Make sure you set the namespace if you changed it from App and also modify the line where it's setting the user in the context so it works with your users table.

Now we need to drop the current StreamHandler from monolog. Laravel sets this up by default and as far as I can see, there isn't a good way to stop Laravel from doing this.

in app/Providers/AppServiceProvider, we should modify the boot() function to do remove the handler and insert the new one. Add the following...

// Get the underlying instance of monolog
$monolog = \Log::getMonolog();

// Instantiate a new handler.
$customStreamHandler = new \App\Handlers\CustomStreamHandler(storage_path('logs/laravel.log'));

// Set the handlers on monolog.  Note this would remove all existing handlers.
$monolog->setHandlers([$customStreamHandler]);

Solution 2

This is a much easier solution but also not exactly what you are looking for (but it might still work for you).

Add the following to AppServiceProvider.php boot().

Log::listen(function()
{
    Log::debug('Additional info', ['user' => Auth::check() ? Auth::user()->name : 'guest']);
});

This will simply listen for any logging and also log a debug line containing user information.

user1669496
  • 32,176
  • 9
  • 73
  • 65