Laravel Log 設定與使用

Laravel Log 說明:

Laravel 日誌基於「 通道 (Channels)」。每個通道 (Channels)代表一種寫入日誌信息的特定方式。例如,single 通道是將日誌寫入到單個日誌文件中。而 slack 通道是將日誌發送到 Slack 上。基於它們的重要程度,日誌可以被寫入到多個通道中去。

在底層,Laravel 利用 Monolog 庫,它為各種強大的日誌處理程序提供了支持。 Laravel 使配置這些處理程序變得輕而易舉,允許您混合和匹配它們,以自定義應用程序的方式完成日誌處理。

設定:

Step01: 在 config\app.php 設定

    'debug' => (bool) env('APP_DEBUG', true), // 啟動詳細偵錯訊息: true|false
    'timezone' => 'Asia/Taipei',  // 時區: UTC | Asia/Taipei

所有應用程序的日誌行為配置選項都位於 config/logging.php 配置文件中。

Single 就是把 log 都寫在同一份,daily表示每天產生一份log,其中的days表示要保存最近幾天內的logs,以這個例子而言,超過14天的都會被自動刪除。

Step02: .env 檔設定日誌(LOG)通道 (Channels)

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
Log Level:

LOG_LEVEL會把大於等於目前level的都print出來,log級別順序由上到下為:emergency、alert、critical、error、warning、notice、info 、debug,由於預設log level為debug,所以所有級別的log都會print出來。

these log levels are: emergencyalertcriticalerrorwarningnoticeinfo, and debug.

Step03: 偵錯記錄

use Illuminate\Support\Facades\Log;

public function login(Request $request)
    {
        Log::debug($request);
        if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')->plainTextToken; 
            $success['name'] =  $user->name;            
   
            return $this->sendResponse($success, 'User login successfully.');
        } 
        else{ 
            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
        } 
    }

Step04: 查看 Log

可以在 storage\logs\{APP_NAME}.log 查看 log

Step05: 時區

可以發現log紀錄的時間慢了8個小時,要修改 config\app.php 中的 timezone: 改為 Asia/Taipei

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *