parent
00de2f37bc
commit
5b7f404842
@ -0,0 +1,58 @@
|
||||
import logging
|
||||
import pymongo
|
||||
import platform
|
||||
import datetime
|
||||
|
||||
|
||||
class Telemetry:
|
||||
def __init__(self, db_url, db_name):
|
||||
self.logger = self.setup_logging()
|
||||
self.db = self.setup_db(db_url, db_name)
|
||||
|
||||
def setup_logging(self):
|
||||
logger = logging.getLogger("telemetry")
|
||||
logger.setLevel(logging.DEBUG)
|
||||
handler = logging.StreamHandler()
|
||||
handler.setFormatter(
|
||||
logging.Formatter(
|
||||
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
)
|
||||
)
|
||||
logger.addHandler(handler)
|
||||
return logger
|
||||
|
||||
def setup_db(self, db_url, db_name):
|
||||
client = pymongo.MongoClient(db_url)
|
||||
return client[db_name]
|
||||
|
||||
def capture_device_data(self):
|
||||
data = {
|
||||
"system": platform.system(),
|
||||
"node": platform.node(),
|
||||
"release": platform.release(),
|
||||
"version": platform.version(),
|
||||
"machine": platform.machine(),
|
||||
"processor": platform.processor(),
|
||||
"time": datetime.datetime.now(),
|
||||
}
|
||||
return data
|
||||
|
||||
def send_to_db(self, collection_name, data):
|
||||
collection = self.db[collection_name]
|
||||
collection.insert_one(data)
|
||||
|
||||
def log_and_capture(self, message, level, collection_name):
|
||||
if level == "info":
|
||||
self.logger.info(message)
|
||||
elif level == "error":
|
||||
self.logger.error(message)
|
||||
data = self.capture_device_data()
|
||||
data["log"] = message
|
||||
self.send_to_db(collection_name, data)
|
||||
|
||||
def log_import(self, module_name):
|
||||
self.logger.info(f"Importing module {module_name}")
|
||||
module = __import__(module_name, fromlist=["*"])
|
||||
for k in dir(module):
|
||||
if not k.startswith("__"):
|
||||
self.logger.info(f"Imported {k} from {module_name}")
|
@ -1,45 +0,0 @@
|
||||
import logging
|
||||
import agentops
|
||||
|
||||
class AgentOpsWrapper:
|
||||
"""
|
||||
A wrapper for the AgentOps client that adds error handling and logging.
|
||||
"""
|
||||
|
||||
def __init__(self, api_key):
|
||||
"""
|
||||
Initialize the AgentOps client with the given API key.
|
||||
"""
|
||||
self.client = agentops.Client(api_key)
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.logger.setLevel(logging.INFO)
|
||||
|
||||
def record_action(self, action_name):
|
||||
"""
|
||||
Record an action with the given name.
|
||||
"""
|
||||
def decorator(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
try:
|
||||
self.client.record_action(action_name)
|
||||
result = func(*args, **kwargs)
|
||||
self.logger.info(f"Action {action_name} completed successfully.")
|
||||
return result
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error while recording action {action_name}: {e}")
|
||||
raise
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
def end_session(self, status):
|
||||
"""
|
||||
End the session with the given status.
|
||||
"""
|
||||
try:
|
||||
self.client.end_session(status)
|
||||
self.logger.info(f"Session ended with status {status}.")
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error while ending session: {e}")
|
||||
raise
|
||||
|
||||
# agentops = AgentOpsWrapper(api_key)
|
@ -0,0 +1,46 @@
|
||||
import os
|
||||
|
||||
|
||||
def parse_log_file(filename: str):
|
||||
"""
|
||||
Parse a log file and return a list of log entries.
|
||||
|
||||
Each log entry is a dictionary with keys for the timestamp, name, level, and message.
|
||||
|
||||
Args:
|
||||
filename (str): The name of the log file.
|
||||
|
||||
Returns:
|
||||
list: A list of log entries.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the log file does not exist.
|
||||
ValueError: If a log entry does not have the correct format.
|
||||
"""
|
||||
# Check if the file exists
|
||||
if not os.path.exists(filename):
|
||||
raise FileNotFoundError(
|
||||
f"The file {filename} does not exist."
|
||||
)
|
||||
|
||||
log_entries = []
|
||||
|
||||
with open(filename, "r") as file:
|
||||
for line in file:
|
||||
parts = line.split(" - ")
|
||||
# Check if the log entry has the correct format
|
||||
if len(parts) != 4:
|
||||
raise ValueError(
|
||||
f"The log entry '{line}' does not have the"
|
||||
" correct format."
|
||||
)
|
||||
timestamp, name, level, message = parts
|
||||
log_entry = {
|
||||
"timestamp": timestamp,
|
||||
"name": name,
|
||||
"level": level,
|
||||
"message": message.rstrip("\n"),
|
||||
}
|
||||
log_entries.append(log_entry)
|
||||
|
||||
return log_entries
|
Loading…
Reference in new issue