root = \dirname($k->getRootDir()) . '/var/log'; $this->dateFormat = (string)$dateFormat; $this->maxFileSize = 20; $this->debugLevel = (int)$debugLevel; } /** * check if actual level is loggable * * @param $level * @return bool */ private function isLoggable($level): bool { if($this->root === '' || empty($this->root)) return false; if($this->debugLevel === 0) return true; $pass = [ '0' => self::LDEBUG, '1' => self::LNOTICE, '2' => self::LWARNING, '3' => self::LERROR ]; $max = \count($pass); for( $i= $this->debugLevel ; $i < $max ; $i++ ){ if($pass[$i] === $level) return true; } return false; } /** * * usage in Controller e.g. : $this->get('net15.core.custom.log')->log('Connected to /user/edit', * CustomLogService::LDEBUG, false,'panel'); * * @param string $line * @param string $level * @param bool $verbose * @param string $section * @return bool */ public function log(string $line, $level = self::LNOTICE, bool $verbose = false, string $section = ''): bool { if(!$this->isLoggable($level)) return false; $line = date($this->dateFormat).' ['.$level.'] - '.$_SERVER['REMOTE_ADDR'].' : '.$_SERVER['REQUEST_URI'].' => '.$line; if($verbose){ $line .= ' - User-Agent: '.$_SERVER['HTTP_USER_AGENT']; if(isset($_SERVER['HTTP_REFERER'])) $line .= ' - ref:'.$_SERVER['HTTP_REFERER']; $line .= ' $_POST : '.json_encode($_POST).' - $_GET '.json_encode($_GET); } if(!empty($section)){ $section = '.'.$section; } $file = $this->root.'/'.'log'.$section.'.txt'; return $this->writeInFile($line,$file); } /** * write a new line in log and rotate if needed * * @param $line * @param $file * @return bool */ private function writeInFile($line, $file): bool { touch($file); $file = realpath($file); if(is_file($file) && filesize($file) > (($this->maxFileSize*1024)*1024)){ rename($file,$file.time().'.log'); touch($file); } if(!is_writable($file)) return false; file_put_contents($file, $line.PHP_EOL, FILE_APPEND); return true; } }