溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Laravel如何重寫日志

發布時間:2021-03-20 10:31:06 來源:億速云 閱讀:300 作者:小新 欄目:開發技術

這篇文章將為大家詳細講解有關Laravel如何重寫日志,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

更改目的:

  • 重寫了日志格式

  • 加入trace,一次請求的唯一標識

  • 加入error級別信息推送,事例中使用企業微信群助手

  • 讓我們可以更及時、更優雅、更方便追蹤日志信息

  • 有助于初學者了解Laravel框架

1。將文件 AppTool.php、Logger.php、LogServiceProvider.php復制到 app/Providers文件夾下,將文件BaseCommand.php復制到App\Console

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

'providers' => [
 ……
 // 注冊日志
  App\Providers\LogServiceProvider::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('\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],,

修改方式就如下方代碼

……
    // 注入全局容器
    $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代碼塊:

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如何重寫日志”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女