Skip to content

Commit 5e1533d

Browse files
committed
feat: add /logs command for admins to query GCP error logs natively
1 parent 26ad718 commit 5e1533d

3 files changed

Lines changed: 466 additions & 0 deletions

File tree

bot_logic.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -564,7 +564,51 @@ async def actualizarRiver(context: ContextTypes.DEFAULT_TYPE):
564564
await actualizarConciertos(context)
565565

566566

567+
async def get_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
568+
user_id = update.effective_user.id
569+
if user_id not in admin_ids:
570+
return
571+
572+
try:
573+
from google.cloud import logging as gcp_logging
574+
import html
575+
576+
await update.message.reply_text("Buscando errores en Google Cloud Logging...")
577+
client = gcp_logging.Client()
578+
579+
# Query logs for the cloud_run_revision with severity>=ERROR
580+
filter_str = 'resource.type="cloud_run_revision" AND severity>=ERROR AND resource.labels.service_name="dcubabot"'
581+
entries = client.list_entries(filter_=filter_str, order_by=gcp_logging.DESCENDING, max_results=10)
582+
583+
log_msgs = []
584+
for entry in entries:
585+
# GCP logs can have payload in text_payload or json_payload
586+
payload = entry.payload
587+
if isinstance(payload, dict):
588+
import json
589+
payload = json.dumps(payload)
590+
elif payload is None:
591+
payload = str(entry.resource)
592+
593+
log_msgs.append(f"[{entry.timestamp.strftime('%Y-%m-%d %H:%M:%S')}] {payload}")
594+
595+
if not log_msgs:
596+
await update.message.reply_text("✅ No se encontraron errores recientes en GCP.")
597+
return
598+
599+
msg = "\n\n".join(log_msgs)
600+
# Split message if it's too long for Telegram (4096 chars limit)
601+
for i in range(0, len(msg), 3800):
602+
chunk = msg[i:i+3800]
603+
await update.message.reply_text(f"Últimos errores:\n<pre>{html.escape(chunk)}</pre>", parse_mode=ParseMode.HTML)
604+
except Exception as e:
605+
await update.message.reply_text(f"Error al leer logs (¿falta permiso roles/logging.viewer en la Service Account?): {e}")
606+
567607
COMMANDS = {
608+
'logs': {
609+
'handler': get_logs,
610+
'description': '(Admin) Revisa los últimos 10 errores en GCP.'
611+
},
568612

569613
'listarlabos': {
570614
'handler': listarlabos,

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ readme = "README.md"
66
requires-python = ">=3.11"
77
dependencies = [
88
"beautifulsoup4",
9+
"google-cloud-logging>=3.15.0",
910
"icalevents",
1011
"psycopg2-binary",
1112
"python-telegram-bot[webhooks]==22.0",

0 commit comments

Comments
 (0)