import os from datetime import datetime class Logger: def __init__(self, log_file_path: str): self.log_file = log_file_path self._init_log_file() def _init_log_file(self): """Initialize log file if it doesn't exist""" log_dir = os.path.dirname(self.log_file) if not os.path.exists(log_dir): os.makedirs(log_dir) if not os.path.exists(self.log_file): try: with open(self.log_file, "w", encoding="utf-8") as f: f.write("") except Exception as e: print(f"Error initializing log file {self.log_file}: {e}") def append_log(self, message: str) -> None: """Append a message to the log file with timestamp.""" try: timestamp = datetime.now().strftime("[%H:%M:%S] ") lines = message.split("\n") lines_with_timestamp = [ f"{timestamp}{line}\n" for line in lines if line.strip() ] if lines_with_timestamp: with open(self.log_file, "a", encoding="utf-8") as f: f.writelines(lines_with_timestamp) except Exception as e: print(f"Error writing to log file {self.log_file}: {e}") def read_log(self, lines_limit: int = None) -> str: """Read the log file, optionally limiting to the last N lines""" try: with open(self.log_file, "r", encoding="utf-8") as f: if lines_limit is None: return f.read() else: # Read all lines and get the last N lines all_lines = f.readlines() if len(all_lines) <= lines_limit: return "".join(all_lines) else: return "".join(all_lines[-lines_limit:]) except Exception as e: print(f"Error reading log file {self.log_file}: {e}") return "" def clear_log(self) -> bool: """Clear the log file""" try: with open(self.log_file, "w", encoding="utf-8") as f: f.write("") return True except Exception as e: print(f"Error clearing log file {self.log_file}: {e}") return False