Laravel Framework Realizes Operation Log Recording Using Middleware
- 2021-10-15 10:03:12
- OfStack
In this paper, an example is given to describe the implementation of Laravel framework using middleware to record operation logs. Share it for your reference, as follows:
Operation logging process using middleware:
1. Create middleware
php artisan make:middleware AdminOperationLog
2. The file is generated./app/Http/Middleware/AdminOperationLog. php
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['admin_uid'] = $user_id;
if('GET' != $request->method()){
$input = $request->all();
$log = new OperationLog(); # Create tables in advance, 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(); # Record a log
}
return $next($request);
}
}
3. Middleware introduction./app/Http/Kernel. php
protected $middlewareGroups = [
'web' => [
...
\App\Http\Middleware\AdminOperationLog::class,
...
],
'api' => [
'throttle:60,1',
'bindings',
],
];
At this time, the operation log will be recorded when the operation is performed
More readers interested in Laravel can check the topics of this site: "Introduction and Advanced Tutorial of Laravel Framework", "Summary of Excellent Development Framework of php", "Introduction Tutorial of php Object-Oriented Programming", "Introduction Tutorial of php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"
I hope this article is helpful to the PHP programming based on Laravel framework.