123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133 |
- <?php /** Created by Anton on 21.07.2020. */
- namespace app\models;
- use app\models\entity\Tasks;
- use app\models\entity\Accounts;
- class ElasticLog
- {
- const LOG_PATH = 'runtime/logs/elastic/';
- /**
- * Пишет в api/runtime/logs/elastic/tasks.log строку:
- * [Дата-время] <Событие (текстом)> "Наименование команды" (<ИД задачи>, <литера секции>, <ИД типа задачи>)...
- * (<ИД проекта>, <серия локо>, <номер локо>) (<ИД исполнителя>, <имя исполнителя>)
- *
- * @param int $commandId
- * @param string $eventName
- *
- * @return bool
- */
- public static function command(int $commandId, $eventName = 'Создание')
- {
- if (!$commandId) return false;
- try {
- $command = Tasks::findOne($commandId);
- $task = Tasks::findOne($command->parent_id);
- $commandType = $command->tasktypes;
- $employee = Accounts::findOne($task->assignees_arr ?? 0);
- $taskString = '(' . ($task->id ?? 0) . ', "' . ($task->tasktypes->letter ?? '?') . '", ' . ($task->tasktypes->id ?? 0) . ')';
- $projectString = '(' . ($task->project->id ?? 0) . ', "' . ($task->project->loco_type ?? '') . '", ' . ($task->project->loco_number ?? 0) . ')';
- $employeeString = '(' . ($employee->id ?? 0) . ', "' . ($employee->name ?? '') . '")';
- if ($eventName == 'Создание') {
- $text = $eventName . ' "' . $commandType->name ?? '';
- } else {
- $text = $eventName . ' "' . ($commandType->name ?? '') . '" ' . $taskString . ' ' . $projectString . ' ' . $employeeString;
- }
- self::log($text);
- return true;
- } catch (\Exception $e) {
- self::error('command:' . $e->getMessage());
- return false;
- }
- }
- /**
- * Запись в Пишет в api/runtime/logs/elastic/eipp.log строку:
- * [Дата-время] <Событие (текстом)>: <uuid работы>, <uuid пользователя>, <данные запроса\ответа>
- *
- * @param mixed $data данные запроса\ответа
- * @param string $workId uuid работы
- * @param int $userId uuid пользователя
- * @param bool $request данные запроса\ответа
- *
- * @return bool
- */
- public static function eipp($data, $workId, $userId = 0, $request = true)
- {
- if (is_array($data)) $data = serialize($data);
- try {
- $text = ($request ? 'запрос' : 'ответ') . ': ';
- $text .= '"' . ($workId ?? '') . '", ';
- $text .= ($userId ?? 0) . ', ';
- $text .= $data;
- self::log($text, 'eipp');
- return true;
- } catch (\Exception $e) {
- self::error('eipp: ' . $e->getMessage());
- return false;
- }
- }
- /**
- * Записывает $text в лог файл с названием 'Y-m-d', добавляя в начало $text дату и время в квардратных скобках
- *
- * @param string $text
- * @param string $dir
- */
- protected static function log(string $text, string $dir = 'commands')
- {
- $logDir = self::getLogDir();
- if (!is_dir($logDir)) mkdir($logDir);
- $fileName = date_create()->format('Y-m-d');
- $dir = $logDir . $dir . '/' . $fileName . '.txt';
- file_put_contents($dir, self::getDateString() . ' ' . $text . "\n", FILE_APPEND);
- }
- /**
- * Пишет сообщение об ошибке в errors.txt
- *
- * @param $msg
- */
- protected static function error($msg)
- {
- $fileName = self::getLogDir() . 'errors.txt';
- file_put_contents($fileName, self::getDateString() . ' ' . $msg . "\n", FILE_APPEND);
- }
- /**
- * Возвращает дату, обрамлённую в квадратные скобки
- *
- * @return string
- */
- protected static function getDateString()
- {
- try {
- $date = new \DateTime();
- } catch (\Exception $e) {
- $date = date_create();
- }
- return '[' . $date->format('d.m.Y H:i:s') . ']';
- }
- /**
- * Возвращает путь к папке с логами
- *
- * @return string
- */
- protected static function getLogDir()
- {
- return \Yii::$app->basePath . '/' . self::LOG_PATH;
- }
- }
|