ssd-logging-daemon.py
Script en Python que gestiona la escritura de registros JSON en la SSD con una política de rotación de archivos.
Asegúrese de que la SSD esté montada en /mnt/ssd. El BPI-5202 admite SSD para almacenamiento confiable. Este script evita la corrupción de datos durante cortes de energía mediante escritura secuencial, pero requiere un sistema de archivos con registro (ext4) recomendado.
ssd-logging-daemon.py
import os
import json
import time
from datetime import datetime
import shutil
LOG_DIR = '/mnt/ssd/logs'
MAX_SIZE = 10 * 1024 * 1024 # 10 Mo par fichier
MAX_FILES = 10
# Vérifier et créer le répertoire sur le SSD monté
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
print(f"Répertoire {LOG_DIR} créé.")
def log_data(sensor_id, value):
timestamp = datetime.now().isoformat()
entry = {"timestamp": timestamp, "sensor": sensor_id, "value": value}
# Nom de fichier basé sur la date pour faciliter la rotation
filename = f"data_{datetime.now().strftime('%Y%m%d')}.json"
filepath = os.path.join(LOG_DIR, filename)
# Vérifier la taille du fichier
if os.path.exists(filepath) and os.path.getsize(filepath) > MAX_SIZE:
# Rotation simple : renommer avec un suffixe
backup_name = f"{filename}.bak.{int(time.time())}"
os.rename(filepath, os.path.join(LOG_DIR, backup_name))
print(f"Rotation effectuée: {backup_name}")
# Écrire les données
with open(filepath, 'a') as f:
f.write(json.dumps(entry) + '\n')
# Nettoyage des anciens fichiers de sauvegarde si trop nombreux
files = [f for f in os.listdir(LOG_DIR) if f.endswith('.bak')]
if len(files) > MAX_FILES:
files.sort(key=lambda x: os.path.getctime(os.path.join(LOG_DIR, x)))
for f in files[:len(files)-MAX_FILES]:
os.remove(os.path.join(LOG_DIR, f))
if __name__ == "__main__":
print("Démarrage du logger SSD...")
counter = 0
while True:
# Simulation de données de capteur
log_data("TempSensor_01", 25.5 + (counter % 10) * 0.1)
counter += 1
time.sleep(5)