yii記錄api接口執(zhí)行時間的方法-創(chuàng)新互聯(lián)

這篇文章主要介紹yii記錄api接口執(zhí)行時間的方法,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

創(chuàng)新互聯(lián)建站溝通電話:18980820575,為您提供成都網(wǎng)站建設(shè)網(wǎng)頁設(shè)計(jì)及定制高端網(wǎng)站建設(shè)服務(wù),創(chuàng)新互聯(lián)建站網(wǎng)頁制作領(lǐng)域十余年,包括混凝土攪拌站等多個領(lǐng)域擁有多年建站經(jīng)驗(yàn),選擇創(chuàng)新互聯(lián)建站,為企業(yè)保駕護(hù)航。

在 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("%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接口執(zhí)行時間的方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

網(wǎng)站標(biāo)題:yii記錄api接口執(zhí)行時間的方法-創(chuàng)新互聯(lián)
鏈接地址:http://www.muchs.cn/article48/epchp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、網(wǎng)頁設(shè)計(jì)公司、云服務(wù)器、面包屑導(dǎo)航、網(wǎng)站導(dǎo)航、網(wǎng)站內(nèi)鏈

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

手機(jī)網(wǎng)站建設(shè)