本篇文章為大家帶來了關於laravel的相關知識,其中主要介紹了關於使用中間件記錄使用者請求日誌的相關問題,包括了建立中間件、註冊中間件、記錄用戶訪問等等內容,下面一起來看一下,希望對大家有幫助。
【相關推薦: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; } }
【相關推薦:laravel影片教學】
以上是實例詳解laravel使用中間件記錄使用者請求日誌的詳細內容。更多資訊請關注PHP中文網其他相關文章!