<?php
 class Logger {
 private static $log_file;
 private static $file;
 private static $log_level = 0;
 private static function createLogFile() {
 $logsDirPath = ROOT_PATH . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs';
 if (!file_exists($logsDirPath)) {
 mkdir($logsDirPath, 0777, true);
 }
 $logsDirPath .= DIRECTORY_SEPARATOR;
 $date = date('Y-m-d');
 static::$log_file = $logsDirPath . "log-{$date}
.txt";
 if (!file_exists(static::$log_file)) {
 $f = fopen(static::$log_file, 'w');
 if(!$f) return false;
 fclose($f);
 }
 return true;
 }
 public static function info($message) {
 if(!static::$log_level) static::$log_level = \Config::getAppConfig('log_level', 1);
 if(static::$log_level == 5) return;
 static::writeLog('INFO', $message, debug_backtrace(2, 1));
 }
 public static function debug($message) {
 if(!static::$log_level) static::$log_level = \Config::getAppConfig('log_level', 1);
 if(static::$log_level != 1) return;
 static::writeLog('DEBUG', $message, debug_backtrace(2, 1));
 }
 public static function warning($message) {
 if(!static::$log_level) static::$log_level = \Config::getAppConfig('log_level', 1);
 if(static::$log_level > 3) return;
 static::writeLog('WARNING', $message, debug_backtrace(2, 1));
 }
 public static function error($message) {
 static::writeLog('ERROR', $message, debug_backtrace(2, 1));
 }
 public static function fatal($message) {
 if(!static::$log_level) static::$log_level = \Config::getAppConfig('log_level', 1);
 if(static::$log_level > 2) return;
 static::writeLog('FATAL', $message, debug_backtrace(2, 1));
 }
 private static function writeLog($logLevel, $logMsg, $bt) {
 if(!static::createLogFile()) return;
 static::openLog();
 if(!static::$file) return;
 $time = date('Y-m-d H:i:s');
 if(!empty($bt[0])) {
 $caller = $bt[0];
 $btLine = $caller['line'];
 $btPath = substr($caller['file'], strlen(ROOT_PATH));
 }
 else {
 $btLine = "[N/A]";
 $btPath = "[N/A]";
 }
 fwrite(static::$file, "[{$time}
] - [{$logLevel}
] - [{$btPath}
] - [{$btLine}
]: {$logMsg}
" . PHP_EOL);
 static::closeFile();
 }
 private static function openLog() {
 $openFile = static::$log_file;
 static::$file = fopen($openFile, 'a') or exit("Can't open $openFile!");
 }
 private static function closeFile() {
 if (static::$file) {
 fclose(static::$file);
 }
 }
 }
