本篇文章给大家带来了关于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中文网其他相关文章!