【Laravel】api接口全局记录日志


直接上代码吧。全局路由中间件

<?php

namespace AppHttpMiddleware;



use Closure;
use IlluminateSupportFacadesDB;
use IlluminateSupportFacadesLog;
use IlluminateSupportFacadesCache;

class ApiRoute
{   
    /**
     * 路由全局中间件
     *
     * @param  IlluminateHttpRequest  $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;

转载:https://www.cnblogs.com/richerdyoung/p/13841347.html

 

 

 

-----------------------------------------------------------------------------------------------

Laravel5.8 API 接口请求,出现问题,烦请指教

这个问题 百度上也没有个方向是指,返回的数据必须是 response->json 不能是 json_encode ,
实际这个问题出现时 是 api 接口请求时出现的,也看到这个中间件时限制 api 请求频率的,但是报的这个错误,确实不清楚怎么出现的 ,烦请各位不吝赐教!!!

中间件中不能用 json_encode
使用 return response ()->json (array ('code' => ErrorCode::NOT_LOGIN, 'msg' => ErrorMsg::$errorMsg [ErrorCode::NOT_LOGIN])); 就好了。
原文:https://blog.csdn.net/qq_32534555/article/...

————————————————
原文作者:FirstBlood
转自链接:https://learnku.com/laravel/t/28552
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请保留以上作者信息和原文链接。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM