首页 > 编程知识 正文

Laravel 重写日志让日志更优雅,如何让自己变得更优雅

时间:2023-05-05 01:35:44 阅读:246727 作者:3654

更改目的:

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

将文件 AppTool.php、Logger.php、LogServiceProvider.php复制到 app/Providers文件夹下,
将文件BaseCommand.php复制到AppConsole下

在config/app.php→providers中加入

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

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

// php-fpm方式调用 日志路径 /opt/logs/xxx.log /opt/logs/xxx.errorLog::info("info");Log::debug("debug");Log::error("error");// 在cli方式调用 日志路径 /opt/clogs/xxx.log /opt/clogs/xxx.errorapp('cLog')->info("info");app('cLog')->debug("debug");app('cLog')->error("error");

在日志级别为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); }

日志内容

// cli模式下的[2019-11-11 17:50:01] local.INFO: [app:partner-counselor src:127.0.0.1 time:406 trace:20ba14b9 url:AppConsoleCommandsTrailPushMessage@handle href:N] 推送未锁定商机信息-未锁定: 结束执行// php-fpm模式下[2019-11-08 18:58:57] local.INFO: [app:partner-counselor src:127.0.0.1 time:36 trace:3633ccee url:GEThttp://127.0.0.1:50111/api/customers/348 href:N] 请求的数据为:{"token":"bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6NTAxMTFcL2FwaVwvYXV0aFwvbG9naW4iLCJpYXQiOjE1NzMyMDQwMzAsImV4cCI6MTU3MzgwODgzMCwibmJmIjoxNTczMjA0MDMwLCJqdGkiOiJZV2RsMU9PdFBOMTV3ZmNZIiwic3ViIjo2LCJwcnYiOiIyNTE5NzdjOTQ4NzExYTE4NDQyNGQ1ZDFmNjQ4Y2U0Mjg1NzQ5YmQwIn0.KTA7a8v5jw80O2WrXMHeVsJSeiv194hsTYHQEn_2KCo"}

注意事项:

修改如下代码不同版本bind部分会有所不同,具体根据IlluminateFoundationApplication::registerCoreContainerAliases中log信息修改。
如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::info、IlluminateConsoleCommand::line、IlluminateConsoleCommand::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 命令行输出:

具体文件请移步github
github项目地址

主要概念 文件存储 UFS如何使用CSS设置div半透明的效果私有云产品更新推荐系统MostPopular算法用Python实现方式

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。