我在 Laravel 7.3 上使用同时运行的多个作业构建项目。 我需要让每个作业将日志写入不同的每日轮换文件。日志文件的名称应基于作业正在处理的模型。
问题是我找不到智能解决方案。
我尝试过的:
1) 在 config/logging.php
中创建多个 channel 。
这按预期工作,但目前大约有 50 个不同的职位,而且数量还在不断增加。方法丑陋且难以维护。
2) 设置 Config(['logging.channels.CUSTOMCHANNEL.path' => storage_path('logs/platform/'.$this->platform->name.'.log')]);
。
乱用 Config 变量是个坏主意,因为许多作业一次运行。因此,来自一个作业的消息通常会写入另一个作业日志中。
3) 使用 Log::useDailyFiles()
似乎这从 laravel 5.5 或 5.6 开始就停止工作了。刚收到错误 Call to undefined method Monolog\Logger::useDailyFiles()
。关于如何在 Laravel 7 中工作有什么想法吗?
4) 在 config/logging.php
中为 channel 使用 tap
参数。
Example in laravel docs 不知道如何将模型名称传递到 CustomizeFormatter 以设置文件名。
我几乎可以肯定有智能解决方案,但我只是遗漏了一些东西。 有什么建议吗?谢谢!
最佳答案
您可以继承日志管理器以允许动态配置
<?php
namespace App\Log;
use Illuminate\Support\Str;
use Illuminate\Log\LogManager as BaseLogManager;
class LogManager extends BaseLogManager
{
/**
* Get the log connection configuration.
*
* @param string $name
* @return array
*/
protected function configurationFor($name)
{
if (!Str::contains($name, ':')) {
return parent::configurationFor($name);
}
[$baseName, $model] = explode(':', $name, 2);
$baseConfig = parent::configurationFor($baseName);
$baseConfig['path'] = ...; //your logic
return $baseConfig;
}
}
Laravel 的日志服务提供者也一样,只是这个可以完全替换掉
<?php
namespace App\Log;
use Illuminate\Support\ServiceProvider;
class LogServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('log', function ($app) {
return new LogManager($app);
});
}
}
编辑:我刚刚看到 config/app.php
中缺少 Laravel 的日志服务提供程序,这是因为应用程序“硬加载”了它。您仍然可以通过继承应用程序本身来替换它
<?php
namespace App\Foundation;
use App\Log\LogServiceProvider;
use Illuminate\Events\EventServiceProvider;
use Illuminate\Routing\RoutingServiceProvider;
use Illuminate\Foundation\Application as BaseApplication;
class Application extends BaseApplication
{
/**
* Register all of the base service providers.
*
* @return void
*/
protected function registerBaseServiceProviders()
{
$this->register(new EventServiceProvider($this));
$this->register(new LogServiceProvider($this));
$this->register(new RoutingServiceProvider($this));
}
}
最后在 bootstrap/app.php
中,将 Illuminate\Foundation\Application
替换为 App\Foundation\Application
例如,如果你试试这个
app('log')->channel('single:users')->debug('test');
Laravel 将使用 single
channel 的配置并写入 users.log
如果你的解析逻辑是
$baseConfig['path'] = $model + '.log';
关于php - Laravel 7 在作业类中动态设置日志路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61029053/