1:  2:  3:  4:  5:  6:  7:  8:  9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 
<?php


namespace SAREhub\Commons\Logger;


use Monolog\Formatter\FormatterInterface;
use Monolog\Handler\HandlerInterface;
use Monolog\Handler\StreamHandler;
use Monolog\Processor\PsrLogMessageProcessor;
use SAREhub\Commons\Misc\InvokableProvider;

class StreamLoggerFactoryProvider extends InvokableProvider
{
    const DEFAULT_LOGGING_LEVEL = "DEBUG";

    const DEFAULT_STREAM = 'php://stdout';
    /**
     * @var string
     */
    private $level;

    /**
     * @var FormatterInterface
     */
    private $formatter;

    public function __construct(
        string $level = self::DEFAULT_LOGGING_LEVEL,
        ?FormatterInterface $formatter,
        $stream = self::DEFAULT_STREAM
    )
    {
        $this->level = $level;
        $this->formatter = $formatter ?? new DefaultJsonLogFormatter();
        $this->stream = $stream;
    }

    public function get(): LoggerFactory
    {
        return BasicLoggerFactory::newInstance()
            ->addProcessor(new PsrLogMessageProcessor())
            ->addHandler($this->createHandler());
    }

    private function createHandler(): HandlerInterface
    {
        $output = new StreamHandler($this->stream, $this->level);
        $output->setFormatter($this->formatter);
        return $output;
    }
}