-
Notifications
You must be signed in to change notification settings - Fork 5
/
telemetry_logger.py
151 lines (135 loc) · 5.4 KB
/
telemetry_logger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import requests
import time
import os
import uuid
from logger import logger
from config_util import get_config_value
telemetryURL = get_config_value('telemetry', 'TELEMETRY_ENDPOINT_URL', None)
ENV_NAME = get_config_value('telemetry', 'SERVICE_ENVIRONMENT', None)
TELEMETRY_LOG_ENABLED = get_config_value('telemetry', 'TELEMETRY_LOG_ENABLED', None).lower() == "true"
telemetry_id = get_config_value('telemetry', 'service_id', None)
telemetry_ver = get_config_value('telemetry', 'service_ver', None)
actor_id = get_config_value('telemetry', 'actor_id', None)
channel = get_config_value('telemetry', 'channel', None)
pdata_id = get_config_value('telemetry', 'pdata_id', None)
events_threshold = get_config_value('telemetry', 'events_threshold', None)
class TelemetryLogger:
"""
A class to capture and send telemetry logs using the requests library with threshold limit.
"""
def __init__(self, url=telemetryURL, threshold=int(events_threshold)):
self.url = url
self.events = [] # Store multiple events before exceeding threshold
self.threshold = threshold
def add_event(self, event):
"""
Adds a telemetry event to the log.
**kwargs:** Keyword arguments containing the event data.
"""
logger.info(f"Telemetry event: {event}")
if not TELEMETRY_LOG_ENABLED:
return
self.events.append(event)
# Send logs if exceeding threshold
if len(self.events) >= self.threshold:
self.send_logs()
def send_logs(self):
"""
Sends the captured telemetry logs using the requests library.
"""
try:
data = {
"id": telemetry_id,
"ver": telemetry_ver,
"params": {"msgid": str(uuid.uuid4())},
"ets": int(time.time() * 1000),
"events": self.events
}
headers = {"Content-Type": "application/json"}
response = requests.post(self.url + "/v1/telemetry", json=data, headers=headers)
response.raise_for_status()
logger.debug(f"Telemetry API request data: {data}")
logger.info("Telemetry logs sent successfully!")
# Reset captured events after sending
self.events = []
except requests.exceptions.RequestException as e:
logger.error(f"Error sending telemetry log: {e}", exc_info=True)
def prepare_interect_event(self, eventInput: dict, etype="TOUCH"):
"""
Prepare a telemetry event dictionary with the specified values.
Args:
eventInput: Event Input.
etype: Event type (default: "api_access")
Returns:
A dictionary representing the telemetry event data.
"""
data = {
"eid": "INTERACT",
"ets": int(time.time() * 1000), # Current timestamp
"ver": "3.1", # Version
"mid": f"INTERACT:{round(time.time())}", # Unique message ID
"actor": {
"id": actor_id,
"type": "System",
},
"context": {
"channel": channel,
"pdata": {
"id": pdata_id,
"ver": "1.0",
"pid": "telegrambot"
},
"env": ENV_NAME
},
"edata": {
"type": etype,
"level": eventInput.get("subtype"),
"id": eventInput.get("edataId") + "-sakhi",
"pageid": eventInput.get("edataId") + "-sakhi",
"extra": {
"pos": []
}
}
}
if eventInput.get("x-request-id", None):
data["context"]["sid"] = eventInput.get("x-request-id")
if eventInput.get("x-device-id", None):
data["context"]["did"] = eventInput.get("x-device-id")
eventCData = self.__getEventCData(eventInput)
if eventCData:
data["context"]["cdata"] = eventCData
return data
def __getEventCData(self, eventInput: dict):
eventCData = []
if eventInput.get("x-consumer-id", None) and eventInput.get("x-source", None):
eventCData = [
{
"id": eventInput.get("x-consumer-id"),
"type": "ConsumerId"
},
{
"id": eventInput.get("x-source"),
"type": "Source"
}
]
return eventCData
def __getEventEDataParams(self, eventInput: dict):
eventEDataParams = [
{"method": str(eventInput.get("method"))},
{"url": str(eventInput.get("url"))},
{"status": eventInput.get("status_code")},
{"duration": int(eventInput.get("duration"))}
]
flattened_dict = self.__flatten_dict(eventInput.get("body", {}))
for item in flattened_dict.items():
eventEDataParams.append({item[0]: item[1]})
return eventEDataParams
def __flatten_dict(self, d, parent_key='', sep='_'):
flattened = {}
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict):
flattened.update(self.__flatten_dict(v, new_key, sep=sep))
else:
flattened[new_key] = v
return flattened