Last active
February 5, 2019 16:53
-
-
Save Ellrion/4134fd820b30e06ddbb49365573e888f to your computer and use it in GitHub Desktop.
Add info about auth user for log in Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Services\Foundation\Log; | |
use Illuminate\Contracts\Auth\Authenticatable; | |
use Illuminate\Contracts\Foundation\Application; | |
use Illuminate\Contracts\Support\Arrayable; | |
use Illuminate\Contracts\Support\Jsonable; | |
/** | |
* use it in ServiceProvider | |
* $this->app->make('log')->getMonolog()->pushProcessor(new LaravelUserProcessor($this->app)); | |
*/ | |
class LaravelUserProcessor | |
{ | |
/** | |
* @var Application | |
*/ | |
protected $app; | |
/** | |
* @param Application $app | |
*/ | |
public function __construct(Application $app) | |
{ | |
$this->app = $app; | |
} | |
/** | |
* @param array $record | |
* | |
* @return array | |
*/ | |
public function __invoke(array $record) | |
{ | |
$user = $this->app->make(Authenticatable::class); | |
if (null === $user) { | |
$record['extra']['user'] = ($this->app->runningInConsole() ? 'cli' : 'guest'); | |
} else { | |
$record['extra']['user']['id'] = $user->getAuthIdentifier(); | |
$record['extra']['user']['data'] = $this->getUserData($user); | |
} | |
return $record; | |
} | |
/** | |
* Get information about user object | |
* | |
* @param $user | |
* @return string | |
*/ | |
protected function getUserData($user) | |
{ | |
if ($user instanceof Jsonable) { | |
return $user->toJson(); | |
} | |
if ($user instanceof Arrayable) { | |
return json_encode($user->toArray()); | |
} | |
return serialize($user); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment