I am having a wrapper class for monolog as below
log.php
<?php
namespace Plugin\Core;
use Monolog\Handler\StreamHandler;
use Monolog\Level;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
class Log
{
private $logger;
private $path;
public function __construct($name = 'wpmatrimony', $path = NULL)
{
if(empty($path)){
$path = WPMATRIMONY_PLUGIN_DIR.'./logs/'.$name.'.log';
}
$this->path = $path;
$this->logger = new Logger($name);
$this->logger->setTimezone(new \DateTimeZone('ASIA/KOLKATA'));
}
private function handler($level){
// https://stackoverflow.com/questions/13968967/how-not-to-show-last-bracket-in-a-monolog-log-line
$handler = new StreamHandler($this->path, $level);
$dateFormat = "d-m-Y H:i:s";
$handler->setFormatter(new LineFormatter(NULL, $dateFormat, false, true));
return $handler;
}
public function info($log){
$this->logger->pushHandler($this->handler(Level::Info));
$this->logger->info($log);
}
public function debug($log){
$this->logger->pushHandler($this->handler(Level::Debug));
$this->logger->debug($log);
}
public function error($log){
$this->logger->pushHandler($this->handler(Level::Error));
$this->logger->error($log);
}
public function warning($log){
$this->logger->pushHandler($this->handler(Level::Warning));
$this->logger->warning($log);
}
public function notice($log){
$this->logger->pushHandler($this->handler(Level::Notice));
$this->logger->notice($log);
}
public function critical($log){
$this->logger->pushHandler($this->handler(Level::Critical));
$this->logger->critical($log);
}
public function alert($log){
$this->logger->pushHandler($this->handler(Level::Alert));
$this->logger->alert($log);
}
public function emergency($log){
$this->logger->pushHandler($this->handler(Level::Emergency));
$this->logger->emergency($log);
}
}
This is working fine. But i am getting the logs increment for each lines, in below case
$log = new Log('test-monolog');
$log->debug('debug');
$log->info('info');
$log->warning('warning');
Actual Output
[30-07-2022 09:41:50] test-monolog.DEBUG: debug
[30-07-2022 09:41:50] test-monolog.INFO: info
[30-07-2022 09:41:50] test-monolog.INFO: info
[30-07-2022 09:41:50] test-monolog.WARNING: warning
[30-07-2022 09:41:50] test-monolog.WARNING: warning
[30-07-2022 09:41:50] test-monolog.WARNING: warning
Expected Output
[30-07-2022 09:47:22] test-monolog.DEBUG: debug
[30-07-2022 09:47:22] test-monolog.INFO: info
[30-07-2022 09:47:22] test-monolog.WARNING: warning
If my code is like below, i am getting expected output
$log = new Log('test-monolog');
$log->debug('debug');
$log = new Log('test-monolog');
$log->info('info');
$log = new Log('test-monolog');
$log->warning('warning');
How can i avoid calling the Log class multiple times?