在实际项目中,我们会被通知需要记录一些日志,方便问题验证。但是,如果日志太多,很容易混淆。请求、响应、执行日志无法对应。这时候就需要为跟踪请求标记一个唯一的ID。/***记录请求日志**ClassApiLog*@packageApp\Library\Components\Elog*/classApiLog{static$logPath;私人静态$单例;/***单例*@returnApiLog*/publicstaticfunctionsingleton(){if(false==self::$singletoninstanceofApiLog){self::$singleton=newstatic();}返回自我::$单例;}protectedfunction__construct($logPath=''){if(empty($logPath)){self::$logPath=ROOT_PATH.'日志/请求/';}else{self::$logPath=ROOT_PATH.$日志路径;}if(!is_dir(self::$logPath)){mkdir(self::$logPath,0777,true);}}publicfunctionrecord($action,$request=[],$type='requestLog'){$headers=[];if(!function_exists('getallheaders')){foreach($_SERVERas$name=>$value){if(substr($name,0,5)=='HTTP_'){$headers[str_replace('','-',strtolower(str_replace('_','',substr($name,5))))]=$value;}}}else{$headers=getallheaders();}//===============加密用户登录密码if(isset($request['password'])){$request['password']=md5(md5($request['密码']));}//===============加密电子邮件if(isset($request['email'])){$request['email']=encrypt_email($request['email']);}//......加密日志中的关键信息//请求更详细的日志记录if('requestLog'==$type){$data=['action'=>$action,'platform'=>PHONE_SYSTEM,'ip'=>real_ip(),'request'=>$request,'REQUEST_URI'=>isset($_SERVER['REQUEST_URI'])?$_SERVER['REQUEST_URI'']:'','headers'=>$headers,];}否则{$数据=['动作'=>$动作,'响应'=>$请求];}$this->write($data,$type);}protectedfunctionwrite($logData,$type){$minutes=date('i');$file=date('Y-m-d-H').'-v'。(间隔($分钟/10))。'。日志';$logData=['request_id'=>static::getRequestId(),'add_time'=>time(),'type'=>$type,'content'=>$logData];file_put_contents(self::$logPath.$file,json_encode($logData).PHP_EOL,FILE_APPEND);}protectedstaticfunctiongetRequestId(){static$requestId='';如果(!empty($requestId)){返回$requestId;}if(function_exists('session_create_id')){$hash=session_create_id();}else{$uid=uniqid('',true);$数据='';$data.=isset($_SERVER['REQUEST_TIME'])?$_SERVER['REQUEST_TIME']:'';$数据.=isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'';$data.=isset($_SERVER['LOCAL_ADDR'])?$_SERVER['LOCAL_ADDR']:'';$data.=isset($_SERVER['LOCAL_PORT'])?$_SERVER['LOCAL_PORT']:'';$data.=isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'';$data.=isset($_SERVER['REMOTE_PORT'])?$_SERVER['REMOTE_PORT']:'';$hash=hash('ripemd128',$uid.md5($data));}$hash=strtoupper($hash);返回$requestId=substr($hash,0,8)。'-'。substr($hash,8,4)。'-'。substr($hash,12,4)。'-'。substr($hash,16,4)。'-'。substr($hash,20,12);}}使用单例,保证一次请求的ID一致ApiLog::singleton()->record($action,$request);ApiLog::singleton()->record($action,$actionData,'createOrder');ApiLog::singleton()->record($action,$errorMessage,'errorHandler');ApiLog::singleton()->record($action,$response,'ResponseLog');
