這篇文章將為大家詳細講解有關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::registerCoreContainerAliases
中log
信息修改。
如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如何重寫日志”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。