Skip to content

Instantly share code, notes, and snippets.

@williamespindola
Last active February 5, 2018 00:46
Show Gist options
  • Save williamespindola/572542e18bd812957661cccdfe1e4472 to your computer and use it in GitHub Desktop.
Save williamespindola/572542e18bd812957661cccdfe1e4472 to your computer and use it in GitHub Desktop.
Implement Monolog with levels and debugger mode
<?php
declare(strict_types=1);
namespace Foo\Bar\Baz;
use Monolog\Logger as Monolog;
use Monolog\Handler\StreamHandler;
class Logger
{
private $infoLog;
private $errorLog;
private $warningLog;
private $level;
private $debug;
public function __construct(Monolog $infoLog, Monolog $errorLog, Monolog $warningLog, bool $debug)
{
$this->infoLog = $infoLog;
$this->errorLog = $errorLog;
$this->warningLog = $warningLog;
$this->debug = $debug;
}
public function setLevel(string $level)
{
$this->level = $level;
}
public function setStreamHandler(string $streamPath, string $logger, string $logConstant)
{
$this->{$logger}->pushHandler(new StreamHandler($streamPath), $logConstant);
}
public function setStreamHanderSameLogFile(string $streamPath)
{
$this->infoLog->pushHandler(new StreamHandler($streamPath), Monolog::INFO);
$this->errorLog->pushHandler(new StreamHandler($streamPath), Monolog::ERROR);
$this->warningLog->pushHandler(new StreamHandler($streamPath), Monolog::WARNING);
}
public function log(string $type, string $message)
{
if ($this->level === '-vvv') {
$this->infoLog->info($message);
}
if ($this->level === '-vv' && $type == 'warning') {
$this->warningLog->warning($message);
}
if ($type === 'error') {
$this->errorLog->error($message);
}
if ($this->debug) {
echo $message . "\n";
}
}
}
<?php
use Monolog\Logger as Monolog;
use Foo\Bar\Baz\Logger;
$settings = [
'debug' => true,
'log-level' => '-vvv',
'log-path' => '/path/to/log/file.log'
];
$logger = new Logger(
new Monolog('info'),
new Monolog('error'),
new Monolog('warning'),
$settings['debug']
);
$logger->setLevel($settings['log-level']);
$logger->setStreamHander($settings['log-path']);
$logger->log('info', 'Ok this is just a info');
$logger->log('warning', 'Be careful');
$logger->log('error', 'holly shit!');
@williamespindola
Copy link
Author

williamespindola commented Feb 5, 2018

Maybe this can work with a variable argument link this:

private $instanceNames = ['infoLog', 'errorLog', 'warningLog'];

public function __construct(bool $debug, Monolog ...$monolog)
{
    $this->debug = $debug;
    foreach($monolog as $k => $monologInstance) {
        $this->{$this->instanceNames[$k]} = $monolog;
    }
}

Is more easy but you is open to a problem because monolog instance must be pass in a sequence that represents $instanceNames.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment