This commit is contained in:
rsgrinko committed 2022-11-03 19:21:56 +03:00
1 parent 6e40d83361
commit 69aeef40a1
1 file changed
+145 -92
+145 -92
View File
@@ -21,12 +21,10 @@
namespace Rsgrinko\Logger;
use Rsgrinko\Logger\LoggerException;
class Log
{
/**
* Уровни логирования
* Возможные уровни логирования
*/
private static $priorityList = [
LOG_DEBUG => 'DEBUG',
@@ -40,45 +38,156 @@
];
/**
* Логирование в файл
*
* @param string $message Сообщение
* @param string $filename Имя файла
* @param mixed $content Дополнительные параметры в виде массива, объекта, строки и т.д.
* @param int $priority Код состояния
* @param string|null $system Название системы
* @param bool $addEnv Флаг необходимости указания расширенных данных
*
* @return int Количество сохранённых байт
* @throws CoreException
* @var string Расположение папки журнала логов
*/
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;
public static $logPath = '';
$logContent = '';
if (!empty($content)) {
if (!is_array($content) && !is_object($content)) {
$content = [$content];
/**
* Установка расположения папки журнала логов
*
* @param string $path Путь до папки журнала логов
*
* @return void
*/
public static function setLogPath(string $path): void
{
self::$logPath = $path;
}
/**
* Получение ОС клиента
*
* @return string ОС клиента
*/
private static function getOS(): string
{
$undefinedOS = 'Unknown OS';
if (empty($_SERVER['HTTP_USER_AGENT'])) {
return $undefinedOS;
}
$oses = [
'iOS' => '/(iPhone)|(iPad)/i',
'Windows 3.11' => '/Win16/i',
'Windows 95' => '/(Windows 95)|(Win95)|(Windows_95)/i',
'Windows 98' => '/(Windows 98)|(Win98)/i',
'Windows 2000' => '/(Windows NT 5.0)|(Windows 2000)/i',
'Windows XP' => '/(Windows NT 5.1)|(Windows XP)/i',
'Windows 2003' => '/(Windows NT 5.2)/i',
'Windows Vista' => '/(Windows NT 6.0)|(Windows Vista)/i',
'Windows 7' => '/(Windows NT 6.1)|(Windows 7)/i',
'Windows 8' => '/(Windows NT 6.2)|(Windows 8)/i',
'Windows 8.1' => '/(Windows NT 6.3)|(Windows 8.1)/i',
'Windows 10' => '/(Windows NT 10.0)|(Windows 10)/i',
'Windows NT 4.0' => '/(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)/i',
'Windows ME' => '/Windows ME/i',
'Open BSD' => '/OpenBSD/i',
'Sun OS' => '/SunOS/i',
'Android' => '/Android/i',
'Linux' => '/(Linux)|(X11)/i',
'Macintosh' => '/(Mac_PowerPC)|(Macintosh)/i',
'QNX' => '/QNX/i',
'BeOS' => '/BeOS/i',
'OS/2' => '/OS/2/i',
'Search Bot' => '/(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp/cat)|(msnbot)|(ia_archiver)/i',
];
foreach ($oses as $os => $pattern) {
if (preg_match($pattern, $_SERVER['HTTP_USER_AGENT'])) {
return $os;
}
$logContent = ' ' . json_encode($content, $jsonOptions);
if (substr($logContent, 0, 4) == ' [{}') {
$logContent = ' #' . str_replace(PHP_EOL, '\n', serialize($content)) . '#';
}
return $undefinedOS;
}
/**
* Получение IP адреса посетителя
*
* @return string IP адрес
*/
private static function getIP(): string
{
$keys = [
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'REMOTE_ADDR',
];
foreach ($keys as $key) {
if (!empty($_SERVER[$key])) {
$ip = trim(end(explode(',', $_SERVER[$key])));
if (filter_var($ip, FILTER_VALIDATE_IP)) {
return $ip;
}
}
}
return 'undefined';
}
/**
* Получение данных текущего окружения
*
* @return array Данные окружения
*/
private static function getEnvironment(): array
{
$result = [
'ip' => self::getIP(),
'os' => self::getOS(),
'memory' => memory_get_usage(true),
];
$_SERVER['SERVER_NAME'] = $_SERVER['SERVER_NAME'] ?? gethostname();
$_SERVER['SERVER_ADDR'] = $_SERVER['SERVER_ADDR'] ?? gethostbyname($_SERVER['SERVER_NAME']);
foreach (['SERVER_ADDR', 'SERVER_NAME', 'HTTP_HOST', 'HTTP_REFERER'] as $value) {
if (!empty($_SERVER[$value])) {
$result[strtolower($value)] = $_SERVER[$value];
}
}
return $result;
}
/**
* Логирование в файл
*
* @param string $text Тестовое сообщение
* @param string $fileName Имя файла лога
* @param mixed $currentContext Контекст (объект, массив, строка...)
* @param int $priority Уровень сообщения
* @param string|null $system Название системы
* @param bool $addEnv Флаг необходимости добавления данные окружения
*
* @return int Количество сохранённых байт
*/
public static function logToFile(
string $text,
string $fileName = '',
$currentContext = null,
int $priority = LOG_DEBUG,
string $system = null,
bool $addEnv = true
): int {
if (!array_key_exists($priority, self::$priorityList)) {
$priority = LOG_DEBUG;
}
$text = str_replace(["\r\n", "\r", "\n"], PHP_EOL, trim($text));
$logFile = empty(trim(self::$logPath)) ? $fileName : self::$logPath . '/' . $fileName;
$logContent = '';
if (!empty($currentContext)) {
if (!is_array($currentContext) && !is_object($currentContext)) {
$currentContext = [$currentContext];
}
$logContent = ' ' . json_encode($currentContext, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (strpos($logContent, ' [{}') === 0) {
$logContent = ' #' . str_replace(PHP_EOL, '\n', serialize($currentContext)) . '#';
}
}
if (empty($system)) {
$backtraceLimit = 2;
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $backtraceLimit);
@@ -91,36 +200,14 @@
$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);
$logText .= str_replace(PHP_EOL, PHP_EOL . str_repeat(' ', $logTextLen), $text);
$logTextPosEOL = strpos($logText, PHP_EOL);
// Собираем информацию об окружении
// При необходимости собираем информацию о текущем окружении
$logEnv = '';
if ($addEnv) {
$env = [
'ip' => SystemFunctions::getIP(),
'os' => SystemFunctions::getOS(),
];
$userId = User::getCurrentUserId();
if (!empty($userId)) {
$objectUser = new User($userId);
$env['userId'] = $objectUser->getId();
$env['userLogin'] = $objectUser->getLogin();
}
$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);
$logEnv = ' ' . json_encode(self::getEnvironment(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
$logText .= $logContent;
@@ -134,38 +221,4 @@
return $result ?: 0;
}
/**
* Метод сохранения логов в Sentry
*
* @param string $sentryMessage Сообщение, передаваемое в Sentry и отображающееся как заголовок Issue
* @param string $sentryErrorLevel Уровень события Sentry (FATAL, ERROR, WARNING, INFO, DEBUG)
* @param array $sentryData Массив данных лога
*
* @return bool
*/
public static function logToSentry(
string $sentryMessage,
string $sentryErrorLevel = 'DEBUG',
array $sentryData = []
): bool {
$sentryErrorLevelArray = ['FATAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'];
if (empty(trim($sentryMessage))
|| !in_array($sentryErrorLevel, $sentryErrorLevelArray)) {
return false;
}
if (is_array($sentryData) && count($sentryData) > 0) {
\Sentry\configureScope(function (\Sentry\State\Scope $sentryScope) use ($sentryData) {
foreach ($sentryData as $paramName => $paramValue) {
$sentryScope->setExtra($paramName, $paramValue);
}
});
}
\Sentry\captureMessage($sentryMessage, \Sentry\Severity::$sentryErrorLevel());
return true;
}
}
}