简体   繁体   中英

Log::info - Logging user logout in laravel.log

I want add all activities inside my app in the larave.log file. I was able to add user login inside it but not the logout.

I do that using Laravel 5.8 with a mysql 5 database.

This is code inside HomeController for registering login user loading home view.

public function index()
{
    Log::info('Utente collegato: '.Auth::user()->name);
    return view( config('configpath.user_home') );// loading user homepage
}

The code below is inside Laravel default LoginController

public function userLogout()
{
    Log::info('User '.Auth::user()->name. 'has logged out');
    Auth::guard('web')->logout();
    return redirect()->route('login');
}

With logout I expect to see the message about user logout as in login but I don't see it. Someone can give me an explanation? Thanks!

You have to override the correct method. I think userLogout gets never called from the framework.

/**
 * Log the user out of the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function logout(Request $request)
{
    Log::info('User '.Auth::user()->email.' has logged out');
    Auth::guard('web')->logout();

    return redirect()->route('login');
}

You can listen for the Login and Logout event to log the actions. To to so, add the following to the boot() method of your EventServiceProvider :

Event::listen(\Illuminate\Auth\Events\Login::class, function ($event) {
    \Log::info("User login: {$event->user->name}");
});

Event::listen(\Illuminate\Auth\Events\Logout::class, function ($event) {
    \Log::info("User logout: {$event->user->name}");
});

Using this method, you don't have to override the existing and framework-provided controller actions.

You need to set a logout method in app/Http/Controllers/Auth/LoginController.php

public function logout(Request $request)
{

  Log::info('User '.Auth::user()->email.' has logged out');

  $this->guard()->logout();

  $request->session()->invalidate();

  return redirect()->route('login');
}

This method will call on log out if you have set default authentication routes and Log will be added on log out in a laravel.log file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM