您可以继承日志管理器以允许动态配置
<?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);
});
}
}
编辑:我刚刚看到 Laravel 的日志服务提供者丢失了config/app.php
,这是因为它是由应用程序“硬加载”的。您仍然可以通过继承应用程序本身来替换它
<?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
通道的配置并写入,users.log
如果您的解析逻辑是
$baseConfig['path'] = $model + '.log';