search
HomeBackend DevelopmentPHP Tutorial制作一个BearyChat的Laravel项目错误日志通知机器人

Laravel 集成 Monolog 来做日志处理,Monolog非常强大,也容易扩展,其实它本身已经支持很多 Handler 了,你可以把日志发送到邮件或者其他日志收集服务器或者系统中,因为我们团队使用 Bearychat 作为团队沟通工具,所以把Laravel项目的实时错误日志推送到Bearychat的一个讨论组中,方便组员迅速发现异常和解决问题 ,其实很简单没多少行代码就搞定了。

  • 首先创建BearyChatHandler
<?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组用来接受通知

    • 新建讨论组,比如叫"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 方法中添加如下代码就可以了:

<?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技术栈笔记

如果觉得本篇文章对您十分有益,何不打赏一下

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment