From 5112e70dd12530851e3518c6b770dffa70a133a5 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Mon, 18 Apr 2022 22:47:21 +0300 Subject: [PATCH] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81=20=D0=BB=D0=BE=D0=B3?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/config.php | 8 +- core/lib/Core/Helpers/Log.class.php | 115 ++++++++++++++++++ .../Core/Helpers/SystemFunctions.class.php | 17 ++- core/lib/Core/Models/DB.class.php | 6 +- index.php | 3 +- 5 files changed, 139 insertions(+), 10 deletions(-) create mode 100644 core/lib/Core/Helpers/Log.class.php diff --git a/core/config.php b/core/config.php index 7099081..a892a26 100644 --- a/core/config.php +++ b/core/config.php @@ -10,6 +10,11 @@ */ define('ROOT_PATH', $_SERVER['DOCUMENT_ROOT']); + /** + * Путь до диреткории с логами + */ + define('LOG_PATH', $_SERVER['DOCUMENT_ROOT'] . '/core/log'); + /** * Префикс таблиц в БД */ @@ -48,4 +53,5 @@ /** * Код значения Да */ - define('CODE_VALUE_Y', 'Y'); \ No newline at end of file + define('CODE_VALUE_Y', 'Y'); + diff --git a/core/lib/Core/Helpers/Log.class.php b/core/lib/Core/Helpers/Log.class.php new file mode 100644 index 0000000..8f87bd7 --- /dev/null +++ b/core/lib/Core/Helpers/Log.class.php @@ -0,0 +1,115 @@ + 'DEBUG', + LOG_INFO => 'INFO', + LOG_NOTICE => 'NOTICE', + LOG_WARNING => 'WARNING', + LOG_ERR => 'ERROR', + LOG_CRIT => 'CRITICAL', + LOG_ALERT => 'ALERT', + LOG_EMERG => 'EMERGENCY', + ]; + + /** + * Логирование в файл + * + * @param string $message Сообщение + * @param string $filename Имя файла + * @param mixed $content Дополнительные параметры в виде массива, объекта, строки и т.д. + * @param int $priority Код состояния + * @param string|null $system Название системы + * @param bool $addEnv Флаг необходимости указания расширенных данных + * + * @return int Количество сохранённых байт + */ + public static function logToFile( + string $message, + string $filename = '', + $content = null, + int $priority = LOG_DEBUG, + string $system = null, + bool $addEnv = true + ): int { + $jsonOptions = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES; + $message = str_replace(["\r\n", "\r", "\n"], PHP_EOL, trim($message)); + $logFile = LOG_PATH . '/' . $filename; + + $logContent = ''; + if (!empty($content)) { + if (!is_array($content) && !is_object($content)) { + $content = [$content]; + } + $logContent = ' ' . json_encode($content, $jsonOptions); + if (substr($logContent, 0, 4) == ' [{}') { + $logContent = ' #' . str_replace(PHP_EOL, '\n', serialize($content)) . '#'; + } + } + + if (!array_key_exists($priority, self::$priorityList)) { + $priority = LOG_DEBUG; + } + + if (empty($system)) { + $backtraceLimit = 2; + $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $backtraceLimit); + if (count($backtrace) < $backtraceLimit) { + $system = pathinfo($backtrace[0]['file'], PATHINFO_FILENAME); + } else { + $system = $backtrace[$backtraceLimit - 1]['function'] ?: pathinfo($backtrace[$backtraceLimit - 1]['file'], PATHINFO_FILENAME); + } + } + + $logText = date('[Y-m-d H:i:s] ') . $system . '.' . self::$priorityList[$priority] . ': '; + $logTextLen = strlen($logText); + $logText .= str_replace(PHP_EOL, PHP_EOL . str_repeat(' ', $logTextLen), $message); + + $logTextPosEOL = strpos($logText, PHP_EOL); + + // Собираем информацию об окружении + $logEnv = ''; + if ($addEnv) { + $env = ['ip' => SystemFunctions::getIP()]; + + $userId = User::getUserId(); + if (!empty($userId)) { + $arUserData = (new User($userId))->getAllUserData(); + $env['userId'] = $arUserData['id']; + $env['userLogin'] = $arUserData['login']; + } + + $env['memory'] = memory_get_usage(true); + + $_SERVER['SERVER_NAME'] = $_SERVER['SERVER_NAME'] ?? gethostname(); + $_SERVER['SERVER_ADDR'] = $_SERVER['SERVER_ADDR'] ?? gethostbyname($_SERVER['SERVER_NAME']); + + $envServerKeys = ['SERVER_ADDR', 'SERVER_NAME', 'HTTP_HOST', 'HTTP_REFERER']; + foreach ($envServerKeys as $value) { + if (!empty($_SERVER[$value])) { + $env[strtolower($value)] = $_SERVER[$value]; + } + } + $logEnv = ' ' . json_encode($env, $jsonOptions); + } + + $logText .= $logContent; + + if (false === $logTextPosEOL) { + $logText .= $logEnv; + } else { + $logText = preg_replace('/\n/', $logEnv . PHP_EOL, $logText, 1); + } + $result = @file_put_contents($logFile, $logText . PHP_EOL, FILE_APPEND | LOCK_EX); + + return $result ?: 0; + } + } \ No newline at end of file diff --git a/core/lib/Core/Helpers/SystemFunctions.class.php b/core/lib/Core/Helpers/SystemFunctions.class.php index f83acbb..0e23337 100644 --- a/core/lib/Core/Helpers/SystemFunctions.class.php +++ b/core/lib/Core/Helpers/SystemFunctions.class.php @@ -113,7 +113,7 @@ /** * Генерация пароля * - * @param int $number Количество символов в пароле + * @param int $number Количество символов в пароле * @param bool $useSpecialChars Использовать ли спецсимволы * * @return string @@ -156,6 +156,7 @@ * Проверка UserAgent на бота * * @param string|null $userAgent User agent + * * @return string|null */ public static function isSearchBot(?string $userAgent): ?string @@ -201,8 +202,9 @@ * Метод для склонения слов в зависимости от числа * Пример: numWord($secs, array('секунда', 'секунды', 'секунд')) * - * @param int $value Число + * @param int $value Число * @param array $words Массив слов + * * @return string */ public static function numWord(int $value, array $words): string @@ -234,6 +236,7 @@ * Преобразование количества секунд в строку с разбиением на дни, часы, минуты и секунды * * @param int $secs Секунды + * * @return string */ public static function secToString(int $secs): string @@ -265,7 +268,9 @@ /** * Удаление GET параметров из строки URL + * * @param string|null $url URL + * * @return string|string[]|null */ public static function getBaseUrl(?string $url = null): ?string @@ -276,8 +281,8 @@ /** * Транслитерация строки * - * @param string|null $text Строка для преобразования - * @param bool $noUseSpace Использование режима "для ЧПУ" + * @param string|null $text Строка для преобразования + * @param bool $noUseSpace Использование режима "для ЧПУ" * * @return string|null */ @@ -320,8 +325,8 @@ /** * Построение структурной таблицы из массива * - * @param array|string|null $var Массив - * @param string $title Заголовок + * @param array|string|null $var Массив + * @param string $title Заголовок * * @return string|null */ diff --git a/core/lib/Core/Models/DB.class.php b/core/lib/Core/Models/DB.class.php index 4b852ae..fbdd592 100644 --- a/core/lib/Core/Models/DB.class.php +++ b/core/lib/Core/Models/DB.class.php @@ -13,11 +13,13 @@ /** * @var object $db Объект базы */ - public object $db; + public object $db; + /** + * @var object|null $instance Объект класса + */ private static ?object $instance = null; - /** * @var int $quantity Количество обращений к базе */ diff --git a/index.php b/index.php index 817e52c..0194c9b 100644 --- a/index.php +++ b/index.php @@ -3,12 +3,13 @@ use Core\CoreException; use Core\ExternalServices\Telegram; use Core\Models\User; - use Core\Helpers\{SystemFunctions, Cache}; + use Core\Helpers\{SystemFunctions, Cache, Log}; require_once $_SERVER['DOCUMENT_ROOT'] . '/core/bootstrap.php'; /*$userId = User::registration('test', '12345', 'support@it-stories.ru', 'user', 'Тестировщик', 'http://samag.ru/uploads/5222447.png'); $user = new User($userId);*/ + Log::logToFile('Проверка работы файлового лога', 'test.log'); $userId = 2;//User::getUserId(); try { $user = new User($userId);