Laravel 整合 Monolog 來做Tlog,Monolog非常強大,也容易擴充,其實它本身已經支援很多 Handler 了,你可以把日誌發送到郵件或者其他日誌收集伺服器或者系統中,因為我們團隊使用 Bearychat 作為團隊溝通工具,所以把Laravel項目的即時錯誤記錄檔推送到Bearychat的一個討論群組中,方便組員迅速發現異常和解決問題 ,其實很簡單沒多少行代碼就搞定了。
data['channel'] = $channel; $this->webhook = $webhook; parent::__construct($level, $bubble); } /** * {@inheritDoc} */ protected function write(array $record) { $postData = [ 'text' => $record['datetime']->format('Y-m-d H:i:s') . '-' . $record["level"] . '-' . $record["level_name"], 'markdown' => false, 'notification' => 'Laravel Error Log', 'attachments' => [ [ 'title' => current(preg_split("/([.\n\r]+)/i", $record['message'])), 'text' => $record['message'], 'color' => '#ffa500' ] ] ]; $postString = json_encode(array_merge($this->data, $postData)); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->webhook); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postString); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json" )); Curl\Util::execute($ch); }}
只要繼承 AbstractProcessingHandler ,重寫 write 方法就可以了, write 中向Bearychat的 webhook 地址POST資料就可以了, $record 是 Monolog 記錄日誌的詳情
-
建立一個BearyChat組用來接受通知
- 建立討論群組,比如叫"Laravel錯誤記錄檔報告"
- 添加機器人到討論群組,點擊 Incoming 添加一個比如叫"Laravel日誌機器人",發送目標選擇上一步建的"Laravel錯誤記錄檔報告",這樣就擷取了 webhook 的URL地址了
- 把相應的人員加到這個討論群組
-
整合 ChearyChatHandler
官方手冊上講到,你像這樣完全控制Monolog
Custom Monolog Configuration
If you would like to have complete control over how Monolog is configured for your application, you may use the application's configureMonologUsing method. You should place a call to this method in your bootstrap/app.php file right before the $app variable is returned by the file:
$app->configureMonologUsing(function($monolog) { $monolog->pushHandler(...); });
return $app;
但是我們除了發送到ChearyChat以外還要保留預設的記錄到log檔案的方式,所以我們不這樣做,我們只要在 Exception Handler 的地方添加一個我們的ChearyChatHandler就可以了。
修改 app/Exceptions/Handler.php ,在 report 方法中添加如下代碼就可以了:
pushHandler(new BearyChatHandler('https://yourhookurl','Laravel日誌機器人')); return parent::report($e); }......}
好了,在代碼中故意寫個錯誤,看看BearyChat收到錯誤記錄檔了。
轉載請註明:轉載自 Ryan是菜鳥 | LNMP技術棧筆記
如果覺得本篇文章對您十分有益,何不打賞一下