Home  >  Article  >  Backend Development  >  Laravel framework implements operation logging function using middleware

Laravel framework implements operation logging function using middleware

不言
不言Original
2018-06-07 09:51:152469browse

This article mainly introduces the Laravel framework to implement the operation logging function using middleware. It analyzes the creation and introduction of the Laravel framework middleware and the related implementation techniques of using the middleware for the operation logging function in the form of examples. What is needed Friends can refer to

. This article describes the example of the Laravel framework implementing the operation logging function using middleware. Share it with everyone for your reference, the details are as follows:

Use middleware for operation logging process:

1. Create middleware

php artisan make:middleware AdminOperationLog

2. The file ./app/Http/Middleware/AdminOperationLog.php

is generated. The code is as follows:

<?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[&#39;admin_uid&#39;] = $user_id;
    if(&#39;GET&#39; != $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 = &#39;&#39;;
      $log->input = json_encode($input, JSON_UNESCAPED_UNICODE);
      $log->save();  # 记录日志
    }
    return $next($request);
  }
}

##3. Introduction of middleware ./app/Http/Kernel.php

protected $middlewareGroups = [
    &#39;web&#39; => [
      ...
      \App\Http\Middleware\AdminOperationLog::class,
      ...
    ],
    &#39;api&#39; => [
      &#39;throttle:60,1&#39;,
      &#39;bindings&#39;,
    ],
  ];

The operation log will be recorded when the operation is performed at this time

Related recommendations:

Laravel framework implementation utilization The listener performs sql statement recording function

The above is the detailed content of Laravel framework implements operation logging function using middleware. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn