64 lines
2.0 KiB
PHP
64 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace HerrleinIT\LogHandler;
|
|
|
|
use GuzzleHttp\Client;
|
|
use HerrleinIT\LogHandler\Handlers\LogForwardingHandler;
|
|
use Illuminate\Contracts\Foundation\Application;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\ServiceProvider;
|
|
use Monolog\Level;
|
|
use Monolog\Logger;
|
|
use Throwable;
|
|
|
|
class LogHandlerServiceProvider extends ServiceProvider
|
|
{
|
|
public function register(): void
|
|
{
|
|
$this->mergeConfigFrom(__DIR__.'/../config/loghandler.php', 'loghandler');
|
|
|
|
$this->app->singleton(LogForwarder::class, function (Application $app): LogForwarder {
|
|
$settings = $app['config']->get('loghandler', []);
|
|
$timeoutSeconds = max(0.0, ((int) ($settings['timeout_ms'] ?? 3000)) / 1000);
|
|
|
|
$client = new Client([
|
|
'timeout' => $timeoutSeconds,
|
|
'connect_timeout' => $timeoutSeconds,
|
|
'http_errors' => false,
|
|
]);
|
|
|
|
return new LogForwarder($app['config'], $client);
|
|
});
|
|
}
|
|
|
|
public function boot(): void
|
|
{
|
|
if ($this->app->runningInConsole()) {
|
|
$this->publishes([
|
|
__DIR__.'/../config/loghandler.php' => $this->app->configPath('loghandler.php'),
|
|
], 'loghandler-config');
|
|
}
|
|
|
|
Log::extend('loghandler', function (Application $app, array $config = []): Logger {
|
|
$logger = new Logger($config['name'] ?? 'loghandler');
|
|
$levelOption = $config['level'] ?? null;
|
|
|
|
try {
|
|
$level = $levelOption === null
|
|
? Level::Debug
|
|
: Level::fromName(strtoupper((string) $levelOption));
|
|
} catch (Throwable) {
|
|
$level = Level::Debug;
|
|
}
|
|
|
|
$logger->pushHandler(new LogForwardingHandler(
|
|
$app->make(LogForwarder::class),
|
|
$level,
|
|
! isset($config['bubble']) || (bool) $config['bubble'],
|
|
));
|
|
|
|
return $logger;
|
|
});
|
|
}
|
|
}
|