Artikel ini membawakan anda pengetahuan yang berkaitan tentang laravel Ia terutamanya memperkenalkan isu berkaitan tentang menggunakan perisian tengah untuk merekodkan log permintaan pengguna, termasuk mencipta perisian tengah, mendaftarkan perisian tengah dan merekodkan akses pengguna dan kandungan lain, mari kita ambil perhatian. lihat di bawah, semoga bermanfaat untuk semua.
[Cadangan berkaitan: tutorial video laravel]
php artisan make:middleware 中间件名称(TraceRecordMiddleware)
$app->middleware([ App\Http\Middleware\TraceRecordMiddleware::class ]);
<?php namespace App\Http\Middleware; use Illuminate\Http\Request; /** * Class TraceRecordMiddleware * @package App\Http\Middleware */ class TraceRecordMiddleware { public function handle(Request $request, \Closure $next) { $response = $next($request); return $response; } }
<?php namespace App\Http\Middleware; use App\Model\SystemTraceRecord; use Illuminate\Http\Request; /** * Class TraceRecordMiddleware * @package App\Http\Middleware */ class TraceRecordMiddleware { public function handle(Request $request, \Closure $next) { //插入数据库日志表 SystemTraceRecord::create([ 'method' => $request->getMethod(), 'secure' => $request->getScheme(), 'uri' => $request->getRequestUri(), 'port' => $request->getPort() ]); return $next($request); } }
<?php namespace App\Http\Middleware; use App\Model\SystemTraceRecord; use Illuminate\Http\Request; /** * Class TraceRecordMiddleware * @package App\Http\Middleware */ class TraceRecordMiddleware { public function handle(Request $request, \Closure $next) { $response = $next($request); //响应后插入数据 SystemTraceRecord::create([ 'data' => json_encode($request->all(), JSON_UNESCAPED_UNICODE), 'response' => $response->getContent() ?: '', 'status' => $response->getStatusCode() ]); return $response; } }
<?php namespace App\Http\Middleware; use App\Model\SystemTraceRecord; use Illuminate\Http\Request; /** * Class TraceRecordMiddleware * @package App\Http\Middleware */ class TraceRecordMiddleware { public function handle(Request $request, \Closure $next) { $response = $next($request); $session = app('session'); SystemTraceRecord::create([ 'user_id' => $session->get('user_info.id', '未知'), 'username' => $session->get('user_info.username', '未知'), 'method' => $request->getMethod(), 'secure' => $request->getScheme(), 'uri' => $request->getRequestUri(), 'response' => $response->getContent() ?: '', 'status' => $response->getStatusCode() ]); return $response; } }
[Cadangan berkaitan: tutorial video laravel]
Atas ialah kandungan terperinci Contoh terperinci laravel menggunakan middleware untuk merekodkan log permintaan pengguna. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!