добавил во все варнинги время с мс

This commit is contained in:
2025-11-03 21:38:14 +03:00
parent 6c03ec4bf2
commit 68fc410b3f

View File

@@ -272,6 +272,7 @@ def start_live_threads(season, game_id):
def stop_live_threads(): def stop_live_threads():
"""Гасим только live-треды.""" """Гасим только live-треды."""
global threads_live global threads_live
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
if not threads_live: if not threads_live:
logger.info("[threads] LIVE threads stopped (nothing to stop)") logger.info("[threads] LIVE threads stopped (nothing to stop)")
return return
@@ -283,12 +284,12 @@ def stop_live_threads():
for t in threads_live: for t in threads_live:
t.join(timeout=2) t.join(timeout=2)
if t.is_alive(): if t.is_alive():
logger.warning(f"[threads] LIVE thread is still alive: {t.name}") logger.warning(f"[{current_time}] [threads] LIVE thread is still alive: {t.name}")
still_alive.append(t.name) still_alive.append(t.name)
threads_live = [] threads_live = []
if still_alive: if still_alive:
logger.warning(f"[threads] Some LIVE threads did not stop: {still_alive}") logger.warning(f"[{current_time}] [threads] Some LIVE threads did not stop: {still_alive}")
else: else:
logger.info("[threads] LIVE threads stopped") logger.info("[threads] LIVE threads stopped")
@@ -311,7 +312,7 @@ def get_data_from_API(
): ):
did_first_fetch = False did_first_fetch = False
while not stop_event.is_set(): while not stop_event.is_set():
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
if stop_when_live and globals().get("STATUS") == "live" and did_first_fetch: if stop_when_live and globals().get("STATUS") == "live" and did_first_fetch:
logger.info(f"{[{current_time}]} [{name}] stopping because STATUS='live' and first fetch done") logger.info(f"{[{current_time}]} [{name}] stopping because STATUS='live' and first fetch done")
break break
@@ -320,16 +321,16 @@ def get_data_from_API(
value = requests.get(url, timeout=5).json() value = requests.get(url, timeout=5).json()
did_first_fetch = True # помечаем, что один заход сделали did_first_fetch = True # помечаем, что один заход сделали
except json.JSONDecodeError as json_err: except json.JSONDecodeError as json_err:
logger.warning(f"{[{current_time}]} [{name}] Ошибка парсинга JSON: {json_err}") logger.warning(f"[{current_time}] [{name}] Ошибка парсинга JSON: {json_err}")
value = {"error": f"JSON decode error: {json_err}"} value = {"error": f"JSON decode error: {json_err}"}
except requests.exceptions.Timeout: except requests.exceptions.Timeout:
logger.warning(f"{[{current_time}]} [{name}] Таймаут при запросе {url}") logger.warning(f"[{current_time}] [{name}] Таймаут при запросе {url}")
value = {"error": "timeout"} value = {"error": "timeout"}
except requests.exceptions.RequestException as req_err: except requests.exceptions.RequestException as req_err:
logger.warning(f"{[{current_time}]} [{name}] Ошибка запроса: {req_err}") logger.warning(f"[{current_time}] [{name}] Ошибка запроса: {req_err}")
value = {"error": str(req_err)} value = {"error": str(req_err)}
except Exception as ex: except Exception as ex:
logger.warning(f"{[{current_time}]} [{name}] Неизвестная ошибка: {ex}") logger.warning(f"[{current_time}] [{name}] Неизвестная ошибка: {ex}")
value = {"error": str(ex)} value = {"error": str(ex)}
# Проверяем, нет ли явного статуса ошибки в JSON # Проверяем, нет ли явного статуса ошибки в JSON
@@ -338,7 +339,7 @@ def get_data_from_API(
"fail", "fail",
"no-status", "no-status",
): ):
logger.warning(f"[{name}] API вернул статус '{value.get('status')}'") logger.warning(f"[{current_time}] [{name}] API вернул статус '{value.get('status')}'")
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
results_q.put({"source": name, "ts": ts, "data": value}) results_q.put({"source": name, "ts": ts, "data": value})
@@ -367,6 +368,7 @@ def get_data_from_API(
def results_consumer(): def results_consumer():
while not stop_event.is_set(): while not stop_event.is_set():
# ⬇️ проверяем, не пора ли в оффлайн (отложенный переход) # ⬇️ проверяем, не пора ли в оффлайн (отложенный переход)
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
off_at = globals().get("OFFLINE_SWITCH_AT") off_at = globals().get("OFFLINE_SWITCH_AT")
if off_at is not None and time.time() >= off_at: if off_at is not None and time.time() >= off_at:
# делаем переход ТОЛЬКО если ещё не оффлайн # делаем переход ТОЛЬКО если ещё не оффлайн
@@ -458,12 +460,6 @@ def results_consumer():
team["pointsInRow"] = box_team["pointsInRow"] team["pointsInRow"] = box_team["pointsInRow"]
team["maxPointsInRow"] = box_team["maxPointsInRow"] team["maxPointsInRow"] = box_team["maxPointsInRow"]
# в любом случае сохраняем сам факт, что box-score пришёл
# latest_data[source] = {
# "ts": msg["ts"],
# "data": incoming_status if incoming_status is not None else payload,
# }
elif "live-status" in source: elif "live-status" in source:
latest_data[source] = { latest_data[source] = {
"ts": msg["ts"], "ts": msg["ts"],
@@ -540,7 +536,7 @@ def results_consumer():
except Exception as e: except Exception as e:
logger.warning( logger.warning(
f"results_consumer: live-status postprocess error: {e}" f"[{current_time}] results_consumer: live-status postprocess error: {e}"
) )
else: else:
@@ -593,7 +589,7 @@ def results_consumer():
# ... остальная обработка ... # ... остальная обработка ...
except Exception as e: except Exception as e:
logger.warning("results_consumer error:", repr(e)) logger.warning(f"[{current_time}] results_consumer error: {repr(e)}")
continue continue