zoukankan      html  css  js  c++  java
  • 【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;
    
    
  • 相关阅读:
    Java 浮点数精度丢失
    旧梦。
    luogu6584 重拳出击
    luogu1758 [NOI2009]管道取珠
    luogu4298 [CTSC2008]祭祀
    bzoj3569 DZY Loves Chinese II
    AGC006C Rabbit Exercise
    bzoj1115 [POI2009]石子游戏Kam
    luogu5675 [GZOI2017]取石子游戏
    bzoj3143 [HNOI2013]游走
  • 原文地址:https://www.cnblogs.com/richerdyoung/p/13841347.html
Copyright © 2011-2022 走看看