日志优化目标与功能概述
本次优化的核心目标包括:
- 对默认的日志输出格式进行重构;
- 引入
trace机制,为每次请求生成唯一的追踪标识; - 增加
error级别的实时消息推送功能,本示例以对接企业微信群机器人作为演示场景; - 旨在让日志记录更加规范、优雅,并便于快速定位和追踪问题;
- 同时也有助于初学者深入理解 Laravel 框架的底层日志处理机制;
文件部署与服务注册配置
第一步:将源文件 AppTool.php、Logger.php 以及 LogServiceProvider.php 复制至项目的 app/Providers 目录下,同时将 BaseCommand.php 文件放置到 App\Console 目录中。
调用方式与错误推送逻辑
第二步:在配置文件 config/app.php→providers 中添加相应的服务提供者注册代码。
'providers' => [
……
// 注册日志
App\Providers\LogServiceProvider::class
……
];
第三步:在项目代码中按照以下方式进行调用测试。
// 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");
第四步:当日志记录的级别达到 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);
}
第五步:查看生成的具体日志内容样例。
多版本兼容性与注意事项
实施过程中需注意以下事项:
由于 Laravel 不同版本内部实现差异,修改容器绑定的代码可能有所不同。请根据 \Illuminate\Foundation\Application::registerCoreContainerAliases 方法中关于 log 的具体定义进行调整。例如在 Laravel 6.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所有自定义命令应继承自 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 日志重写以实现更优雅管理的介绍已结束。如需了解更多相关内容,欢迎查阅本站往期文章或继续浏览后续教程,感谢大家的支持!