inpsyde / Wonolog

Monolog-based logging package for WordPress.
https://inpsyde.github.io/Wonolog/
MIT License
173 stars 17 forks source link

[Question]: best practice to lower $errorLogLevel in HttpApiListener #83

Open frugan-dev opened 4 months ago

frugan-dev commented 4 months ago

Description of the bug

Using version 2.x I would need to lower $errorLogLevel in HttpApiListener listener from LogLevel::ERROR to LogLevel::WARNING. The procedure I followed works using PHP-DI (see below), I would like to know if it is the correct one or if there is a better approach.

use Inpsyde\Wonolog\LogLevel;
use Inpsyde\Wonolog\HookListener\HttpApiListener;

return [
    HttpApiListener::class => DI\create()
        ->constructor(DI\value(LogLevel::WARNING)),
];
use Inpsyde\Wonolog\HookListener\HttpApiListener;

add_action(
    'wonolog.setup',
    function (Inpsyde\Wonolog\Configurator $config) use ($container) {
        $config->disableDefaultHookListeners(
                HttpApiListener::class
            )
            ->addActionListener(
                $container->get(HttpApiListener::class)
            )
        ;
    }
);

Initially I also tried to create a custom HttpApiListener class that extended Inpsyde\Wonolog\HookListener\HttpApiListener by overriding the __construct(int $errorLogLevel = LogLevel::WARNING), but then I realized that the Inpsyde\Wonolog\HookListener\HttpApiListener class is defined as final.

Reproduction instructions

.

Expected behavior

.

Environment info

Relevant log output

No response

Additional context

No response

Code of Conduct

gmazzap commented 3 months ago

The default listener classes are final because Wonolog instantiates them using new $listener() so if classes would be extended, the constructor could be extended in a non-compatible way (e.g. requiring mandatory parameters), PHP would not complain, but then a fatal error would happen.

The approach you use looks fine to me. In the end, it is like you want to use a custom listener, but that happens to use the same class as the default handler.

Maybe it would be nice to have a filter to change the log level, so that the constructor could look like:

$errorLogLevel = apply_filters('wonolog.http-error-listener-level', null);
$this->errorLogLevel = LogLevel::normalizeLevel($errorLogLevel) ?? LogLevel::ERROR;

And then you would need to add the filter:

add_filter('wonolog.http-error-listener-level', fn () => LogLevel::WARNING)

But I'm not sure this is actually better than what you're doing.

frugan-dev commented 3 months ago

Hi @gmazzap, and thanks for your help! I think it could be a useful thing to have filters to alter the LogLevels of the default listeners. The alternative routes (e.g. dependecy injector) are not always easily accessible to everyone, or not everyone knows how to do it, so I would find it useful to provide more options available.