在?basecontroller?中繼承父類的?beforeaction?和?afteraction?勾子,記錄api運(yùn)行開始,以及結(jié)束時間。
示例:
private?$actionStart?=?0; private?$actionEnd?=?0; //?beforeAction,?afterAction?用來記錄API請求接口,以及耗時 public?function?beforeAction($action){ ????$this->actionStart?=?microtime(true); ????return?parent::beforeAction($action); ????} ????public?function?afterAction($action,?$result){ ????$this->actionEnd?=?microtime(true); ????$afterAction?=?parent::afterAction($action,?$result); ????//?記錄API請求接口,耗時took ????logInfo(print_r(["api"?=>?request()->url,?"took"?=>?sprintf("%.5f",?$this->actionEnd?-?$this->actionStart)],?true)); ????return?$afterAction;}
(推薦教程:yii框架)
logInfo?日志記錄方法,這個方法是對?YII?info日志的二次封裝
//?yii日志組件記錄日志if?(!function_exists("logInfo"))?{ ????function?logInfo($message,?$category?=?"debug") ????{ ????????//?記錄info日志,用于調(diào)試 ????????$logEnable?=?Yii::$app->params["log_enable"]; ????????if?(is_null($logEnable)?||?$logEnable?===?false)?{ ????????????return; ????????} ????????Yii::info(sprintf("%sntmemory?used?%d?bytes?[%.3f?KB]",?$message,?memory_get_usage(),?memory_get_usage()/1024),?$category); ????}}
日志輸出如下:
2019-03-14?02:46:31?[127.0.0.1][-][-][info][debug]?Array ( ????[api]?=>?/protocol?page=1&limit=12&unit=10m&time[]=1551854884755&time[]=1552459684755&q=&es_type=http&src_ip=&src_port=&dst_ip=&dst_port=&sensor_id=&uids=&prs_debug=1 ????[took]?=>?0.18194 ) ????memory?used?8996368?bytes?[8785.516?KB] ????in?/Users/tophant.yunfei/work/prs-rebirth-php/common/utils/function.php:316 ????in?/Users/tophant.yunfei/work/prs-rebirth-php/backend/controllers/RestBaseController.php:61
Yii-log 配置如下:
[ ????'class'?=>?'yiilogFileTarget', ????'levels'?=>?['info'], ????'categories'?=>?['debug',?'sql',?'elastic',?'py'], ????'logVars'?=>?[], ????'logFile'?=>?'@runtime/logs/info.log' ]
更多編程相關(guān)內(nèi)容,請關(guān)注php中文網(wǎng)yii框架欄目!
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載。
THE END