Heim >Backend-Entwicklung >PHP-Tutorial >制作一个BearyChat的Laravel项目错误日志通知机器人
Laravel 集成 Monolog 来做日志处理,Monolog非常强大,也容易扩展,其实它本身已经支持很多 Handler 了,你可以把日志发送到邮件或者其他日志收集服务器或者系统中,因为我们团队使用 Bearychat 作为团队沟通工具,所以把Laravel项目的实时错误日志推送到Bearychat的一个讨论组中,方便组员迅速发现异常和解决问题 ,其实很简单没多少行代码就搞定了。
<?php namespace App;use Monolog\Handler\AbstractProcessingHandler; use Monolog\Logger; use Monolog\Handler\Curl;class BearyChatHandler extends AbstractProcessingHandler { private $data; private $webhook; public function __construct($webhook, $channel, $level = Logger::NOTICE, $bubble = true) { $this->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组用来接受通知
集成 ChearyChatHandler
官方手册上讲到,你像这样完全控制Monolog
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 方法中添加如下代码就可以了:
<?phpnamespace App\Exceptions;use App\BearyChatHandler; ......use Log;class Handler extends ExceptionHandler { ...... public function report(Exception $e) { $monolog = Log::getMonolog(); $monolog->pushHandler(new BearyChatHandler('https://yourhookurl','Laravel日志机器人')); return parent::report($e); }......}
好了,在代码中故意写个错误,看看BearyChat收到错误日志了。
转载请注明:转载自 Ryan是菜鸟 | LNMP技术栈笔记
如果觉得本篇文章对您十分有益,何不打赏一下