LichessStatTgWeb/LichessClientTG_bot/events.py
vrubelroman d24cc1a2bd structured events.log, count games in the window they finished in, immediate reopened notice
- events.py (bot): one grep-able line per event into data/events.log (10 MB x 5 rotation,
  survives container recreation): user_start, cmd, text/callback/non_text, addgamer_input/
  addgamer_result, addtoken_result, gamer_added, gamer_deleted, period_set, lang_set,
  check (decision=request|skip_unchanged|skip_closed, games, notified, lag), check_error,
  closed_notice, reopened_notice, blocked, token_rejected, status_refresh, admin_notify,
  tg_error; a SUMMARY line at midnight, also shown by admin /status as "Вчера".
  Service side: EVT lichess_429 (kind=concurrency|burst|unknown) and lichess_error in its log.
- /games/{username}/period?by_finish=true: query Lichess from since-3h and keep games with
  since < lastMoveAt <= until. Periodic checks use it, so a game created 14:58 and finished
  15:06 is reported in the 15:00-16:00 window instead of being lost on the boundary.
- reopened-account notice is sent as soon as the status flips, not after the next game.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-20 22:51:11 +00:00

124 lines
4.4 KiB
Python

"""
Structured event log: one compact, grep-able line per thing a user or the
system did, kept apart from the noisy container log.
File: <dir of config.DATABASE_PATH>/events.log (i.e. the data volume, so it
survives container recreation), rotated at 10 MB x 5 backups. Line format:
2026-10-20T22:15:12Z EVT <name> key=value key2=value2 ...
2026-10-20T00:00:01Z SUMMARY date=2026-10-19 users=... checks=... ...
Values: ints as-is, True/False as 1/0, None as "-", strings truncated to 80
chars and repr-quoted when they contain a space or "=". Fields keep the order
they were passed in, so a name's lines always look alike and `grep -c "EVT
gamer_added"` / `grep "uid=12345"` answer the usual questions directly.
Both the bot and the admin-bot process import this and may write to the SAME
file (there is one data volume): that is acceptable here — the handler opens
the file in append mode and lines are short (one write() each), so they
interleave but never corrupt each other. Only the rotation itself can race
(two processes rotating at the same instant); the admin bot writes a handful
of lines a day, so it practically never triggers it.
event() never raises: a logging failure must not break the handler that
called it. The first failure is reported once to the normal logger.
"""
import logging
import os
import time
from logging.handlers import RotatingFileHandler
import config
# NOT getLogger(__name__): this module is named "events", which is exactly the
# dedicated file logger below; the warnings here must reach the container log.
logger = logging.getLogger("bot.events")
EVENTS_LOG_PATH = os.path.join(os.path.dirname(config.DATABASE_PATH), "events.log")
MAX_BYTES = 10 * 1024 * 1024
BACKUP_COUNT = 5
MAX_STR_LEN = 80
_events_logger = None
_setup_failed_reported = False
def _get_logger() -> logging.Logger:
"""Lazily build the dedicated 'events' logger (propagate=False: not in the container log)."""
global _events_logger
if _events_logger is not None:
return _events_logger
lg = logging.getLogger("events")
lg.setLevel(logging.INFO)
lg.propagate = False
if not lg.handlers:
handler = RotatingFileHandler(EVENTS_LOG_PATH, maxBytes=MAX_BYTES, backupCount=BACKUP_COUNT, encoding="utf-8")
handler.setFormatter(logging.Formatter("%(message)s"))
lg.addHandler(handler)
_events_logger = lg
return lg
def _fmt_value(value) -> str:
if value is None:
return "-"
if value is True:
return "1"
if value is False:
return "0"
if isinstance(value, int):
return str(value)
if isinstance(value, float):
return f"{value:.1f}"
s = str(value)
if len(s) > MAX_STR_LEN:
s = s[:MAX_STR_LEN]
if " " in s or "=" in s or s == "":
return repr(s)
return s
def _format_line(kind: str, name: str, fields: dict) -> str:
ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
parts = [ts, kind]
if name:
parts.append(name)
for key, value in fields.items():
parts.append(f"{key}={_fmt_value(value)}")
return " ".join(parts)
def _write(kind: str, name: str, fields: dict) -> None:
global _setup_failed_reported
try:
_get_logger().info(_format_line(kind, name, fields))
except Exception as e:
if not _setup_failed_reported:
_setup_failed_reported = True
logger.warning(f"events.log unavailable ({EVENTS_LOG_PATH}): {e!r}; events will be dropped")
def event(name: str, /, **fields) -> None:
"""Write one `EVT <name> k=v ...` line. Never raises. `name` is positional-only so a field may also be called name= (e.g. cmd name=start)."""
_write("EVT", name, fields)
def summary(**fields) -> None:
"""Write one `SUMMARY k=v ...` line (daily totals, see periodic.daily_counter_reset_task). Never raises."""
_write("SUMMARY", "", fields)
def last_summary_line() -> str:
"""The last SUMMARY line of events.log (used by the admin bot's /status), or '' if none / no file."""
try:
if not os.path.exists(EVENTS_LOG_PATH):
return ""
last = ""
with open(EVENTS_LOG_PATH, "r", encoding="utf-8", errors="replace") as f:
for line in f:
if " SUMMARY " in line:
last = line.rstrip("\n")
return last
except Exception as e:
logger.warning(f"Could not read last SUMMARY from {EVENTS_LOG_PATH}: {e!r}")
return ""