1. 程式人生 > 實用技巧 >laravel 學習筆記之 日誌

laravel 學習筆記之 日誌

日誌

配置

laravel 框架中日誌系統配置位於 config/logging.php 配置檔案中,預設情況下使用 stack 記錄日誌訊息

構建日誌堆疊

'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['syslog', 'slack'],
    ],

    'syslog' => [
        'driver' => 'syslog',
        'level' => 'debug',
    ],

    'slack' => [
        'driver' => 'slack',
        'url' => env('LOG_SLACK_WEBHOOK_URL'),
        'username' => 'Laravel Log',
        'emoji' => ':boom:',
        'level' => 'critical',
    ],
],

stack 通過藉助它的 channels 選項聚合了另外兩個通道: syslog 和 slack

日誌級別

  • debug (100): 詳細的除錯資訊
  • info (200): 使用者登入、SQL 日誌等事件
  • notice (250): 普通但有意義的事件
  • warning (300): 非錯誤的異常,警告資訊
  • error (400): 執行時的錯誤,不需要立即操作,但通常應該被記錄和監視
  • critical (500): 至關重要的條件。示例:應用程式元件不可用,意外異常
  • alert (550): 必須立即採取行動。例如:整個網站宕機,資料庫不可用等。這會觸發簡訊提醒並喚醒你
  • emergency (600): 緊急情況:系統無法使用

以上日誌級別逐級提高

Log::debug('An informational message.');

參照上面的例子,debug 級別的日誌會觸發 syslog 通道,但不會觸發 slack 通道,因為 critical 的級別高於 debug

如果我們記錄一條 emergency 訊息,它將被髮送給 syslog 和 slack,因為 emergency 的級別高於兩個通道的最低級別限制

Log::emergency('The system is down!');

寫入日誌資訊

Log::log('debug',$message);
Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::info($message);
Log::debug($message);

//預設情況下,訊息被寫入到在 config/logging.php 配置檔案中定義的預設日誌通道
Log::log('info', 'Showing user profile for John');
Log::info('Showing user profile for John');
Log::info('User failed to login.', ['id' => $user->id]);
Log::channel('notice')->info('Something happened!'); //指定日誌通道
Log::stack(['single', 'slack'])->info('Something happened!'); //多通道構成的按需記錄的堆疊