-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.py
More file actions
122 lines (102 loc) · 4.61 KB
/
logger.py
File metadata and controls
122 lines (102 loc) · 4.61 KB
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
# ──────────────────────────────────────────────────────────
# Project : Snake_AI
# File : logger.py
# Author : ProGen18
# Created : 02-03-2026
# Modified : 27-03-2026
# Purpose : Handle logging of events and export simulation statistics
# ──────────────────────────────────────────────────────────
# ============================================================
# IMPORTS
# ============================================================
import os
import time
from datetime import datetime
import pandas as pd
# ============================================================
# LOGGER CLASSE
# ============================================================
# ╔══════════════════════════════════════════════════════════╗
# ║ JournalDeBord ║
# ╠══════════════════════════════════════════════════════════╣
# ║ Handles: ║
# ║ • Standard output logging with timestamps ║
# ║ • Storing simulation statistics locally ║
# ║ • Exporting recorded data to Excel (.xlsx) form ║
# ╚══════════════════════════════════════════════════════════╝
class JournalDeBord:
"""
Log events and keep records of simulation statistics.
Attributes:
dossier_logs (str): Directory where logs and exports are saved.
historique_stats (list[dict]): In-memory storage for training records.
heure_debut (datetime): Time when the logger instance was created.
"""
def __init__(self, dossier_logs: str = "logs"):
"""
Initialize the logger.
Args:
dossier_logs (str): The folder path to store log files. Defaults to 'logs'.
"""
self.dossier_logs = dossier_logs
if not os.path.exists(dossier_logs):
os.makedirs(dossier_logs)
self.historique_stats = []
self.heure_debut = datetime.now()
def noter_evenement(self, message: str) -> None:
"""
Print a message to the console with the current timestamp.
Args:
message (str): The text message to log.
"""
heure = time.strftime("%H:%M:%S", time.localtime())
print(f"[{heure}] {message}")
def noter_stats(
self,
nb_parties: int,
epsilon: float,
record: int,
score_moyen: float,
tps: float,
) -> None:
"""
Record a snapshot of the simulation statistics.
Args:
nb_parties (int): Total number of games played.
epsilon (float): Current exploration rate.
record (int): All-time high score reached.
score_moyen (float): Average score of recent games.
tps (float): Simulation speed (ticks per second).
"""
self.historique_stats.append(
{
"timestamp": datetime.now(),
"parties": nb_parties,
"epsilon": epsilon,
"record": record,
"moyenne": score_moyen,
"vitesse_tps": tps,
}
)
def exporter_excel(self) -> str | None:
"""
Export the accumulated simulation stats to an Excel file.
Returns:
str | None: The path to the generated Excel file, or None if failed/empty.
"""
if not self.historique_stats:
self.noter_evenement("Rien à exporter pour l'instant.")
return None
# --- 1. Processing ---
df = pd.DataFrame(self.historique_stats)
# --- 2. Output ---
try:
ts = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
nom_final = f"simulation_{ts}.xlsx"
chemin_final = os.path.join(self.dossier_logs, nom_final)
df.to_excel(chemin_final, index=False)
self.noter_evenement(f"enregistrement dans : {chemin_final}")
return chemin_final
except Exception as e:
self.noter_evenement(f"problème lors de l'export : {e}")
return None