ElasticLog.php 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. <?php /** Created by Anton on 21.07.2020. */
  2. namespace app\models;
  3. use app\models\entity\Tasks;
  4. use app\models\entity\Accounts;
  5. class ElasticLog
  6. {
  7. const LOG_PATH = 'runtime/logs/elastic/';
  8. /**
  9. * Пишет в api/runtime/logs/elastic/tasks.log строку:
  10. * [Дата-время] <Событие (текстом)> "Наименование команды" (<ИД задачи>, <литера секции>, <ИД типа задачи>)...
  11. * (<ИД проекта>, <серия локо>, <номер локо>) (<ИД исполнителя>, <имя исполнителя>)
  12. *
  13. * @param int $commandId
  14. * @param string $eventName
  15. *
  16. * @return bool
  17. */
  18. public static function command(int $commandId, $eventName = 'Создание')
  19. {
  20. if (!$commandId) return false;
  21. try {
  22. $command = Tasks::findOne($commandId);
  23. $task = Tasks::findOne($command->parent_id);
  24. $commandType = $command->tasktypes;
  25. $employee = Accounts::findOne($task->assignees_arr ?? 0);
  26. $taskString = '(' . ($task->id ?? 0) . ', "' . ($task->tasktypes->letter ?? '?') . '", ' . ($task->tasktypes->id ?? 0) . ')';
  27. $projectString = '(' . ($task->project->id ?? 0) . ', "' . ($task->project->loco_type ?? '') . '", ' . ($task->project->loco_number ?? 0) . ')';
  28. $employeeString = '(' . ($employee->id ?? 0) . ', "' . ($employee->name ?? '') . '")';
  29. if ($eventName == 'Создание') {
  30. $text = $eventName . ' "' . $commandType->name ?? '';
  31. } else {
  32. $text = $eventName . ' "' . ($commandType->name ?? '') . '" ' . $taskString . ' ' . $projectString . ' ' . $employeeString;
  33. }
  34. self::log($text);
  35. return true;
  36. } catch (\Exception $e) {
  37. self::error('command:' . $e->getMessage());
  38. return false;
  39. }
  40. }
  41. /**
  42. * Запись в Пишет в api/runtime/logs/elastic/eipp.log строку:
  43. * [Дата-время] <Событие (текстом)>: <uuid работы>, <uuid пользователя>, <данные запроса\ответа>
  44. *
  45. * @param mixed $data данные запроса\ответа
  46. * @param string $workId uuid работы
  47. * @param int $userId uuid пользователя
  48. * @param bool $request данные запроса\ответа
  49. *
  50. * @return bool
  51. */
  52. public static function eipp($data, $workId, $userId = 0, $request = true)
  53. {
  54. if (is_array($data)) $data = serialize($data);
  55. try {
  56. $text = ($request ? 'запрос' : 'ответ') . ': ';
  57. $text .= '"' . ($workId ?? '') . '", ';
  58. $text .= ($userId ?? 0) . ', ';
  59. $text .= $data;
  60. self::log($text, 'eipp');
  61. return true;
  62. } catch (\Exception $e) {
  63. self::error('eipp: ' . $e->getMessage());
  64. return false;
  65. }
  66. }
  67. /**
  68. * Записывает $text в лог файл с названием 'Y-m-d', добавляя в начало $text дату и время в квардратных скобках
  69. *
  70. * @param string $text
  71. * @param string $dir
  72. */
  73. protected static function log(string $text, string $dir = 'commands')
  74. {
  75. $logDir = self::getLogDir();
  76. if (!is_dir($logDir)) mkdir($logDir);
  77. $fileName = date_create()->format('Y-m-d');
  78. $dir = $logDir . $dir . '/' . $fileName . '.txt';
  79. file_put_contents($dir, self::getDateString() . ' ' . $text . "\n", FILE_APPEND);
  80. }
  81. /**
  82. * Пишет сообщение об ошибке в errors.txt
  83. *
  84. * @param $msg
  85. */
  86. protected static function error($msg)
  87. {
  88. $fileName = self::getLogDir() . 'errors.txt';
  89. file_put_contents($fileName, self::getDateString() . ' ' . $msg . "\n", FILE_APPEND);
  90. }
  91. /**
  92. * Возвращает дату, обрамлённую в квадратные скобки
  93. *
  94. * @return string
  95. */
  96. protected static function getDateString()
  97. {
  98. try {
  99. $date = new \DateTime();
  100. } catch (\Exception $e) {
  101. $date = date_create();
  102. }
  103. return '[' . $date->format('d.m.Y H:i:s') . ']';
  104. }
  105. /**
  106. * Возвращает путь к папке с логами
  107. *
  108. * @return string
  109. */
  110. protected static function getLogDir()
  111. {
  112. return \Yii::$app->basePath . '/' . self::LOG_PATH;
  113. }
  114. }