import logging import os import socket import requests from datetime import datetime, timedelta # Configure logging LOG_FILE_PATH = './data/log.txt' logging.basicConfig(filename=LOG_FILE_PATH, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') # Function to delete old logs def delete_old_logs(): log_dir = './data/' log_file = 'log.txt' log_path = os.path.join(log_dir, log_file) if os.path.exists(log_path): file_mod_time = datetime.fromtimestamp(os.path.getmtime(log_path)) if datetime.now() - file_mod_time > timedelta(days=10): os.remove(log_path) log_info_with_server(f"Deleted old log file: {log_file}") else: log_info_with_server(f"Log file is not older than 10 days: {log_file}") else: log_info_with_server(f"Log file does not exist: {log_file}") # Function to read the name (idmasa) from the file def read_name_from_file(): try: with open("./data/idmasa.txt", "r") as file: n_masa = file.readline().strip() return n_masa except FileNotFoundError: logging.error("File ./data/idmasa.txt not found.") return "unknown" # Function to send logs to a remote server def send_log_to_server(log_message, n_masa): try: hostname = socket.gethostname() device_ip = socket.gethostbyname(hostname) log_data = { "hostname": str(hostname), "device_ip": str(device_ip), "nume_masa": str(n_masa), "log_message": str(log_message) } server_url = "http://rpi-ansible:80/logs" # Replace with your server's URL print(log_data) # Debugging: Print log_data to verify its contents response = requests.post(server_url, json=log_data, timeout=5) response.raise_for_status() logging.info("Log successfully sent to server: %s", log_message) except requests.exceptions.RequestException as e: logging.error("Failed to send log to server: %s", e) # Wrapper for logging.info to also send logs to the server def log_info_with_server(message): n_masa = read_name_from_file() # Read name (idmasa) from the file logging.info(message) send_log_to_server(message, n_masa)