这篇文章主要介绍yii记录api接口执行时间的方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
在 BaseController 中继承父类的 beforeAction 和 afterAction 勾子,记录API运行开始,以及结束时间。
示例:
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日志,用于调试
$logEnable = Yii::$app->params["log_enable"];
if (is_null($logEnable) || $logEnable === false) {
return;
}
Yii::info(sprintf("%s\n\tmemory 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' => 'yii\log\FileTarget',
'levels' => ['info'],
'categories' => ['debug', 'sql', 'elastic', 'py'],
'logVars' => [],
'logFile' => '@runtime/logs/info.log'
]
以上是“yii记录api接口执行时间的方法”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。