利用中间件进行操作日志记录过程:

    1、创建中间件

    1. php artisan make:middleware AdminOperationLog

    2、生成了文件./app/Http/Middleware/AdminOperationLog.php

    代码如下:

    1. <?php
    2. namespace App\Http\Middleware;
    3. use Closure;
    4. use Illuminate\Http\Request;
    5. use Illuminate\Support\Facades\Auth;
    6. use App\Http\Models\OperationLog;
    7. class AdminOperationLog
    8. {
    9. /**
    10. * Handle an incoming request.
    11. *
    12. * @param \Illuminate\Http\Request $request
    13. * @param \Closure $next
    14. * @return mixed
    15. */
    16. public function handle($request, Closure $next)
    17. {
    18. $user_id = 0;
    19. if(Auth::check()) {
    20. $user_id = (int) Auth::id();
    21. }
    22. $_SERVER['admin_uid'] = $user_id;
    23. if('GET' != $request->method()){
    24. $input = $request->all();
    25. $log = new OperationLog(); # 提前创建表、model
    26. $log->uid = $user_id;
    27. $log->path = $request->path();
    28. $log->method = $request->method();
    29. $log->ip = $request->ip();
    30. $log->sql = '';
    31. $log->input = json_encode($input, JSON_UNESCAPED_UNICODE);
    32. $log->save(); # 记录日志
    33. }
    34. return $next($request);
    35. }
    36. }

    3、中间件引入 ./app/Http/Kernel.php

    1. protected $middlewareGroups = [
    2. 'web' => [
    3. ...
    4. \App\Http\Middleware\AdminOperationLog::class,
    5. ...
    6. ],
    7. 'api' => [
    8. 'throttle:60,1',
    9. 'bindings',
    10. ],
    11. ];

    此时进行操作时就会记录操作日志