这篇文章主要介绍了Laravel 重写日志,让日志更优雅,laravel框架俗称优雅的框架,所以有想对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'];
});
……
\Illuminate\Console\Command::info、\Illuminate\Console\Command::line、\Illuminate\Console\Command::error,然后所有console继承BaseCommand
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 重写日志内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:Laravel 重写日志,让日志更优雅
基础教程推荐
- php fread函数使用方法总结 2023-01-19
- PHP5.0 TIDY_PARSE_FILE缓冲区溢出漏洞的解决方案 2022-11-26
- PHP中的输出缓冲控制详解 2023-06-03
- 解析PHP中Exception异常机制 2023-06-13
- PHP树形结构tree类用法示例 2022-12-15
- CentOS 7 编译安装PHP7 2023-09-02
- 在laravel中实现事务回滚的方法 2023-02-22
- php+mysql+ajax 局部刷新点赞/取消点赞功能(每个账号只点赞一次) 2023-04-24
- PHP如何将头像图片转换圆形图片 2023-08-30
- PHP设计模式之状态模式定义与用法详解 2022-10-12
