直接上代码吧。全局路由中间件
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
class ApiRoute
{
/**
* 路由全局中间件
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$now_time = time();
$date_now_time = date("Y-m-d H:i:s",$now_time);
$user_id = 0;
if(!empty($request->header('TOKEN'))){
//得到userid
$user_id = '';
}
$request->merge(['sq_time' => microtime(true)]);
$response = $next($request);
$rq_time = microtime(true)-$request->sq_time;
//插入请求日志
$request_url = $request->getRequestUri();
DB::connection('mysql_log_config')
->table("request_log")
->insert([
'user_id'=>$user_id,
'header'=>json_encode($request->header()),
'ip_address'=>$request->ip(),
'method'=>$request->method(),
'url'=>$request->fullUrl(),
'param'=>json_encode($request->all()),
'rq_time'=>sprintf("%.2f",$rq_time),
'response'=>$response->getContent(),
'created_at'=>$now_time,
'updated_at'=>$now_time
]);
return $response;
}
}
SQL
CREATE TABLE `request_log` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL COMMENT '用户ID',
`header` longtext COMMENT '请求头',
`ip_address` varchar(255) DEFAULT NULL COMMENT '客户端IP',
`method` varchar(255) DEFAULT NULL COMMENT '请求方法',
`url` varchar(255) DEFAULT NULL COMMENT '请求url',
`param` longtext COMMENT '请求参数',
`rq_time` float(10,2) DEFAULT NULL COMMENT '响应时间',
`response` longtext COMMENT '响应结果',
`created_at` int(10) DEFAULT NULL,
`updated_at` int(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
|