saqueib's avatar

Error logging is not working when user is logged in

I am getting this weird issue, I have setup slack with Monolog and its sending notification, but when I am logged in there is no notification coming.

class AppServiceProvider extends ServiceProvider {

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->environment('production')) {
            // Get The Logger
            $monolog = Log::getMonolog();
            $monolog->pushProcessor(new WebProcessor($_SERVER));
            $monolog->pushProcessor(function ($record) {

                 $record['extra']['session_id'] = Cookie::get(config('session.cookie'));

                 // Auth::user() is always null, how can i get the logged in user
                 $record['extra']['user'] = \Auth::check() ? 'Name: '.\Auth::user()->name . "\n". url(\Auth::user()->username) : "Guest";
                 $record['extra']['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
                 
                 return $record;
            });

            $slackHandler = new SlackHandler(env('SLACK_TOKEN'), '#sss-sslogs', 'sss-log', true, ':warning:', Logger::ERROR, true, false, true
            );

            $monolog->pushHandler($slackHandler);
        }
    }

I have tried with commenting out $record['extra']['user'] line from above but no luck, I need to logout to make it send notification.

How can i get the Auth::user() in AppServiceProvider its always returning null, or is there anywhere else I can register this SlackHandler

0 likes
4 replies
bobbybouwmann's avatar

I think you can't access the facade in there because it's not loaded yet.. Not sure why Since the Log facade seems to work for you...

However this should work (at least it works for me)

auth()->user()->name
auth()->user()->username

This helper function will call the correct class instead of the facade

function auth() 
{
    return app('Illuminate\Contracts\Auth\Guard');
}
bobbybouwmann's avatar

Are you sure the user is logged in? If auth() returns null you can't access the name of course!

saqueib's avatar

Yes I have checked it, user is logged in and i can access auth()->user() in controller but in AppServiceProvider@boot its returning null and Error Logging is also not working, but when I logout, error logging is working and I am getting User as Guest by this line

$record['extra']['user'] = auth()->check() ? 'Name: '.auth()->user()->name . "\n". url(auth()->user()->username) : "Guest";

I have also tried injecting Guard class in boot method but same problem, its returning null

Please or to participate in this conversation.