如何更好地使用 telescope

fengchezhi發表於2020-06-09

laravel官方telescope是一個強大的開發除錯工具。由於對工具不熟悉,沒法發揮強大工具的強項,所以我花了點時間研究telescope後,得出來一些使用技巧

1. 安裝指導

參考社群文件 telescope

2. 線上環境只寫入檔案日誌

// app/Providers/TelescopeServiceProvider.php
public function register()
{
    // Telescope::night();

    $this->hideSensitiveRequestDetails();

    Telescope::filter(function (IncomingEntry $entry) {
        if (!$this->app->environment('production')) {
            return true;
        }

        Log::info('telescope', $entry->toArray());
        return false;

    });
}

3. telescope_entries記錄數太多了,只想儲存必要的

### 修改laravel .env
TELESCOPE_LOG_WATCHER=false
TELESCOPE_CACHE_WATCHER=false
TELESCOPE_REDIS_WATCHER=false
TELESCOPE_RESPONSE_SIZE_LIMIT=16
TELESCOPE_ENABLED=true

4. 檔案日誌適配elk抓取

建立一個檔案 App\Helpers\Logging\DailyFormatter.php

<?php
namespace App\Helpers\Logging;

class DailyFormatter{
    /**
     * 自定義給定的日誌例項。
     *
     * @param  \Illuminate\Log\Logger  $logger
     * @return void
     */
    public function __invoke($logger)
    {
        foreach ($logger->getHandlers() as $handler) {
            $handler->getFormatter()->allowInlineLineBreaks(false);
        }
    }
}

從config/logging.php複製出daily渠道,並且加上tap中介軟體DailyFormatter

// config/logging.php 裡面有很多Log Channels例如"single", "daily", "slack"等
'daily' => [
    'driver' => 'daily',
    'path' => storage_path('logs/laravel.log'),
    'level' => 'debug',
    'days' => 14,
],
'telescope' => [
    'driver' => 'daily',
    'path' => storage_path('logs/telescope/laravel.log'),
    'level' => 'debug',
    'tap' => [App\Helpers\Logging\DailyFormatter::class],
    'days' => 14,
],

這時要修改以上第二項優化的檔案TelescopeServiceProvider.php

// app/Providers/TelescopeServiceProvider.php
public function register()
{
    // Telescope::night();

    $this->hideSensitiveRequestDetails();

    Telescope::filter(function (IncomingEntry $entry) {
        if (!$this->app->environment('production')) {
            return true;
        }

        Log::channel('telescope')->info($entry->type, $entry->toArray());
        return false;

    });
}

5. 不想記錄高頻率的基礎資料介面,例如國家語言,map欄位等

    // config/telescope.php 增加需要忽略的uri
    'ignore_paths' => [
        'nova-api*',
        'v1/language',
        'v1/country',
        'v1/fieldmap',
        'v1/department',
        'v1/area/*'
    ],

6. 快速搜尋出post和put請求

// app/Providers/TelescopeServiceProvider.php
public function register()
{
    // Telescope::night();

    $this->hideSensitiveRequestDetails();

    Telescope::tag(function (IncomingEntry $entry) {
        if ($entry->type === 'request') {
            return ['method:'.$entry->content['method']];
        }

        return [];
    });

    Telescope::filter(function (IncomingEntry $entry) {

        if (!$this->app->environment('production')) {
            return true;
        }

        Log::channel('telescope')->info($entry->type, $entry->toArray());
        return false;

    });
}

檢視效果
telescope

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章