返回
热门搜索

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

IT博客 运维技术 点击量 371

基本信息 收藏 - 举报 - 海报

详细介绍

更改目的:

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

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

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

"providers" => [
 ……
 // 注册日志
  AppProvidersLogServiceProvider::class
 ……
 ];

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

// 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时,会执行推送,本事例中采用企业微信群推送

  /**
   * 推送错误信息
   * @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("GuzzleHttpClient")->request("POST", $url, [
      GuzzleHttpRequestOptions::JSON=>[
        "msgtype"=> "text",
        "text"=> [
          "content" => $content
        ]
      ]
    ]);
    $body = GuzzleHttpjson_decode($result->getBody()->getContents(), true);
  }

5 。日志内容

注意事项:

修改如下代码不同版本bind部分会有所不同,具体根据IlluminateFoundationApplication::registerCoreContainerAliaseslog信息修改。
如laravel6.x中为"log" => [IlluminateLogLogManager::class, PsrLogLoggerInterface::class],

修改方式就如下方代码

    ……
    // 注入全局容器
    $app->instance("Log", $logger);
    $app->bind("PsrLogLoggerInterface", function (Application $app) {
      return $app["log"]->getLogger();
    });
    $app->bind("IlluminateLogLogManager", function (Application $app) {
      return $app["log"];
    });
    ……
有关console中使用时,建议重写IlluminateConsoleCommand::infoIlluminateConsoleCommand::lineIlluminateConsoleCommand::error,然后所有console继承BaseCommand demo代码块:
use AppConsoleBaseCommand;

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 重写日志内容请搜索IT博客社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT博客社区!

没有更多内容。

用户评价(0)

好评度100%
  • 还没有人评论此条信息!
+ 加载更多

联系方式

提示:联系我时,请说明在看到的,谢谢!
  • 联系人:
  • 地  区:
  • 电  话: 共发布信息(2004)条 所在地:未填写
看了又看
加载中
首页 首页 收藏 收藏

电话联系