Laravel 重写日志,让日志更优雅

吾爱主题 阅读:127 2021-11-09 14:56:00 评论:0

更改目的:

  • 重写了日志格式
  • 加入trace,一次请求的唯一标识
  • 加入error级别信息推送,事例中使用企业微信群助手
  • 让我们可以更及时、更优雅、更方便追踪日志信息
  • 有助于初学者了解Laravel框架

1。将文件 AppTool.phpLogger.phpLogServiceProvider.php复制到 app/Providers文件夹下,将文件BaseCommand.php复制到App\Console

2 。在config/app.php→providers中加入

?
1 2 3 4 5 6 'providers' => [   ……   // 注册日志    App\Providers\LogServiceProvider:: class   ……   ];

3。在项目中使用如下方式调用

?
1 2 3 4 5 6 7 8 // php-fpm方式调用 日志路径 /opt/logs/xxx.log /opt/logs/xxx.error \Log::info( "info" ); \Log::debug( "debug" ); \Log::error( "error" ); // 在cli方式调用 日志路径 /opt/clogs/xxx.log /opt/clogs/xxx.error app( 'cLog' )->info( "info" ); app( 'cLog' )->debug( "debug" ); app( 'cLog' )->error( "error" );

4。在日志级别为error时,会执行推送,本事例中采用企业微信群推送

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24    /**     * 推送错误信息     * @param $message     */    public function pushErrorMessage( $message )    {      $content = "app:" . static ::getAppName() ." src: ". static::getRequestSource() ." trace: ". self::getTrace() ." url: ". static::$uri_info ." error: ". $message ." time: ". date(" Y-m-d H:i:s");      // 测试群      $url = "xxxxxxxxxxxx" ;      $result = app( '\GuzzleHttp\Client' )->request( 'POST' , $url , [        \GuzzleHttp\RequestOptions::JSON=>[          "msgtype" => "text" ,          "text" => [            "content" => $content          ]        ]      ]);      $body = \GuzzleHttp\json_decode( $result ->getBody()->getContents(), true);    }

5 。日志内容

注意事项:

修改如下代码不同版本bind部分会有所不同,具体根据\Illuminate\Foundation\Application::registerCoreContainerAliaseslog信息修改。
如laravel6.x中为'log' => [\Illuminate\Log\LogManager::class, \Psr\Log\LoggerInterface::class],

修改方式就如下方代码

?
1 2 3 4 5 6 7 8 9 10 …… // 注入全局容器 $app->instance('Log', $logger); $app->bind('Psr\Log\LoggerInterface', function (Application $app) {    return $app['log']->getLogger(); }); $app->bind('\Illuminate\Log\LogManager', function (Application $app) {    return $app['log']; }); ……
有关console中使用时,建议重写 \Illuminate\Console\Command::info\Illuminate\Console\Command::line\Illuminate\Console\Command::error,然后所有console继承BaseCommand demo代码块: ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 use App\Console\BaseCommand;   class Demo extends BaseCommand {    protected $signature = 'command:demo' ;    protected $description = 'demo' ;    public function __construct()    {      parent::__construct();    }    public function handle()    {      $this ->info( 'this is info!' );      $this ->line( 'this is line!' );      $this ->error( 'this is error!!!' );    } }

demo 命令行输出:

到此这篇关于Laravel 重写日志,让日志更优雅的文章就介绍到这了,更多相关Laravel 重写日志内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/zhangkaiadl/article/details/103036470

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容