Download the PHP package fanly/log2dingding without Composer
On this page you can find all versions of the php package fanly/log2dingding. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package log2dingding
我们在写代码时,都想自己的代码尽可能的不影响现有的代码。
或者说,最大化不改动任何代码的情况下,如何嵌入我们的新功能?这是我们常说的「非侵入式」的开发方式。
使用「非侵入式」的开发模式,主要在提供第三方插件和功能中最为常见。今天借助「Rollbar」第三方工具来说说如何做到「非侵入式」开发。
本文主要能学到:
- Laravel Event / Listener 原理;
- Rollbar for Laravel 的使用
- 创建一个 Log to Dingding 群的功能
Laravel Event / Listener 原理
在 Laravel,主要利用 EventServiceProvider
来加载 Events / Listeners
:
EventServiceProvider
返回的是 Dispatcher
对象。我们看看 Dispatcher
类:
主要作用是绑定 Events
和 Listeners
,当 Events
触发时,直接执行 Listeners
。
我们希望 log 除了在本地文件存储输出外,也想把 log 信息实时发到其他平台和渠道上,这时候我们就需要借助 LogServiceProvider
的 events / listeners
绑定实现了。现在来看看 LogServiceProvider
:
这里将 $this->app['events']
也就是 Dispatcher
传入,用户事件的注册:
有了 ServiceProvider
和 listen
就可以做到「非入侵」开发了。
Rollbar
Rollbar error monitoring integration for Laravel projects. This library adds a listener to Laravel's logging component. Laravel's session information will be sent in to Rollbar, as well as some other helpful information such as 'environment', 'server', and 'session'.
简单使用
使用该工具,只要在其官网注册账号,并产生一个 access token
即可
安装该工具,也只需要简单的两步:
测试,只要有 Log 输出,rollbar 后台都可以收到信息,方便查看,而再也不需要去看 log 文件了。
剖析实现原理
我们来看看 rollbar 是不是我们所设想的那样实现的?
我们先看看 RollbarServiceProvider
这个比较好理解,先利用 register
注册两个 singleton
,然后在 boot
方法中,注册 listener
其中 $app['log']
,就是我们的上文说的 LogServiceProvider
,将 listener
注册到 EventServiceProvider
中。
最后我们看看 Rollbar
facades 返回的是:RollbarLogHandler
对象
看看 RollbarLogHandler
实现,也主要是将 log 信息反馈到Rollbar 中,此处不做分析了。
模拟实现
通过对 Rollbar
简单的分析,就会发现原来通过简单 Listener
,不用改现在的任何功能和代码,就能实现将 log 实时发到你想接收的地方。
所以我们可以尝试也写一个这样的功能,将 log 信息发到钉钉上。
好了,我们开始写 Log2Dingding
插件。
根据之前的文章我们可以很方便的组织好插件结构:
composer.json
设置:
我们定义 ServiceProvider
:
我们主要是创建一个发钉钉消息的单例,然后再注册 listener
,只要获取 log 信息,就发送信息到钉钉上。
测试一下:
总结
最后做成插件,和 Rollbar
一样,引入:
同样的,其他信息都不需要设置,跑一个测试:
Laravel 框架的一大好处在于,可以以友好的方式实现我们「非入侵」开发,只要借助「ServiceProvider
」和「Events/Listner
」,就可以扩展我们的功能。
参考
- 「12步」制作 Laravel 插件 (一)https://mp.weixin.qq.com/s/AD05BiKjPsI2ehC-mhQJQw
- 「3步」发布 Laravel 插件 (二)https://mp.weixin.qq.com/s/RSYeHU7aR4gyJyLNwdjbJg
- fanly/log2dingding https://packagist.org/packages/fanly/log2dingding