habulaj commited on
Commit
a01e203
·
verified ·
1 Parent(s): c2bb33b

Create logs.py

Browse files
Files changed (1) hide show
  1. routes/logs.py +71 -0
routes/logs.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import aiohttp
4
+ from fastapi import APIRouter, HTTPException
5
+ from typing import List, Dict, Any
6
+
7
+ router = APIRouter()
8
+
9
+ SUPABASE_URL = "https://ussxqnifefkgkaumjann.supabase.co"
10
+ SUPABASE_KEY = os.getenv("SUPA_KEY")
11
+
12
+ if not SUPABASE_KEY:
13
+ raise ValueError("❌ SUPA_KEY não foi definido no ambiente!")
14
+
15
+ SUPABASE_HEADERS = {
16
+ "apikey": SUPABASE_KEY,
17
+ "Authorization": f"Bearer {SUPABASE_KEY}",
18
+ "Content-Type": "application/json"
19
+ }
20
+
21
+ # Logging interno
22
+ logging.basicConfig(level=logging.INFO)
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ @router.get("/logs", response_model=List[Dict[str, Any]])
27
+ async def get_onboarding_logs():
28
+ """
29
+ Retorna os últimos 10 logs relacionados à tabela Onboarding.
30
+ """
31
+ # SQL Query para buscar logs que envolvam a tabela Onboarding e sejam métodos de modificação
32
+ sql_query = """
33
+ select
34
+ cast(timestamp as text) as timestamp,
35
+ m.method,
36
+ m.status_code,
37
+ r.headers ->> 'x-client-info' as client_info,
38
+ r.headers ->> 'authorization' as auth_token,
39
+ r.url
40
+ from edge_logs
41
+ cross join unnest(metadata) as m
42
+ cross join unnest(m.request) as r
43
+ where
44
+ path like '%rest/v1/Onboarding%'
45
+ and m.method in ('POST', 'PATCH', 'PUT', 'DELETE')
46
+ order by
47
+ timestamp desc
48
+ limit 10;
49
+ """
50
+
51
+ async with aiohttp.ClientSession() as session:
52
+ try:
53
+ async with session.post(
54
+ f"{SUPABASE_URL}/rest/v1/rpc/execute_sql",
55
+ json={"sql": sql_query},
56
+ headers=SUPABASE_HEADERS,
57
+ ) as response:
58
+ if response.status != 200:
59
+ error_detail = await response.text()
60
+ logger.error(f"Erro ao consultar logs: {error_detail}")
61
+ raise HTTPException(
62
+ status_code=response.status,
63
+ detail="Erro ao consultar os logs no Supabase",
64
+ )
65
+
66
+ data = await response.json()
67
+ return data
68
+
69
+ except Exception as e:
70
+ logger.exception("Erro inesperado ao consultar logs")
71
+ raise HTTPException(status_code=500, detail=str(e))