laravel 利用中介軟體進行操作日誌記錄
阿新 • • 發佈:2019-01-01
利用中介軟體進行操作日誌記錄過程:
1、建立中介軟體
php artisan make:middleware AdminOperationLog
2、生成了檔案./app/Http/Middleware/AdminOperationLog.php
程式碼如下:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Models\OperationLog;
class AdminOperationLog
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$user_id = 0;
if(Auth::check()) {
$user_id = (int) Auth::id();
}
$_SERVER ['admin_uid'] = $user_id;
if('GET' != $request->method()){
$input = $request->all();
$log = new OperationLog(); # 提前建立表、model
$log->uid = $user_id;
$log->path = $request->path();
$log->method = $request->method();
$log ->ip = $request->ip();
$log->sql = '';
$log->input = json_encode($input, JSON_UNESCAPED_UNICODE);
$log->save(); # 記錄日誌
}
return $next($request);
}
}
3、中介軟體引入 ./app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
...
\App\Http\Middleware\AdminOperationLog::class,
...
],
'api' => [
'throttle:60,1',
'bindings',
],
];
此時進行操作時就會記錄操作日誌