|
|
| import logging
|
| import os
|
| import queue
|
| import sys
|
| import threading
|
| import tkinter as tk
|
| import traceback
|
| from enum import Enum, auto
|
| from pathlib import Path
|
| from typing import Literal
|
|
|
| from serena import constants
|
| from serena.util.logging import MemoryLogHandler
|
|
|
| log = logging.getLogger(__name__)
|
|
|
|
|
| class LogLevel(Enum):
|
| DEBUG = auto()
|
| INFO = auto()
|
| WARNING = auto()
|
| ERROR = auto()
|
| DEFAULT = auto()
|
|
|
|
|
| class GuiLogViewer:
|
| """
|
| A class that creates a Tkinter GUI for displaying log messages in a separate thread.
|
| The log viewer supports coloring based on log levels (DEBUG, INFO, WARNING, ERROR).
|
| It can also highlight tool names in boldface when they appear in log messages.
|
| """
|
|
|
| def __init__(
|
| self,
|
| mode: Literal["dashboard", "error"],
|
| title="Log Viewer",
|
| memory_log_handler: MemoryLogHandler | None = None,
|
| width=800,
|
| height=600,
|
| ):
|
| """
|
| :param mode: the mode; if "dashboard", run a dashboard with logs and some control options; if "error", run
|
| a simple error log viewer (for fatal exceptions)
|
| :param title: the window title
|
| :param memory_log_handler: an optional log handler from which to obtain log messages; If not provided,
|
| must pass the instance to a `GuiLogViewerHandler` to add log messages.
|
| :param width: the initial window width
|
| :param height: the initial window height
|
| """
|
| self.mode = mode
|
| self.title = title
|
| self.width = width
|
| self.height = height
|
| self.message_queue = queue.Queue()
|
| self.running = False
|
| self.log_thread = None
|
| self.tool_names = []
|
|
|
|
|
| self.log_colors = {
|
| LogLevel.DEBUG: "#808080",
|
| LogLevel.INFO: "#000000",
|
| LogLevel.WARNING: "#FF8C00",
|
| LogLevel.ERROR: "#FF0000",
|
| LogLevel.DEFAULT: "#000000",
|
| }
|
|
|
| if memory_log_handler is not None:
|
| for msg in memory_log_handler.get_log_messages():
|
| self.message_queue.put(msg)
|
| memory_log_handler.add_emit_callback(lambda msg: self.message_queue.put(msg))
|
|
|
| def start(self):
|
| """Start the log viewer in a separate thread."""
|
| if not self.running:
|
| self.log_thread = threading.Thread(target=self.run_gui)
|
| self.log_thread.daemon = True
|
| self.log_thread.start()
|
| return True
|
| return False
|
|
|
| def stop(self):
|
| """Stop the log viewer."""
|
| if self.running:
|
|
|
| self.message_queue.put(None)
|
| return True
|
| return False
|
|
|
| def set_tool_names(self, tool_names):
|
| """
|
| Set or update the list of tool names to be highlighted in log messages.
|
|
|
| Args:
|
| tool_names (list): A list of tool name strings to highlight
|
|
|
| """
|
| self.tool_names = tool_names
|
|
|
| def add_log(self, message):
|
| """
|
| Add a log message to the viewer.
|
|
|
| Args:
|
| message (str): The log message to display
|
|
|
| """
|
| self.message_queue.put(message)
|
|
|
| def _determine_log_level(self, message):
|
| """
|
| Determine the log level from the message.
|
|
|
| Args:
|
| message (str): The log message
|
|
|
| Returns:
|
| LogLevel: The determined log level
|
|
|
| """
|
| message_upper = message.upper()
|
| if message_upper.startswith("DEBUG"):
|
| return LogLevel.DEBUG
|
| elif message_upper.startswith("INFO"):
|
| return LogLevel.INFO
|
| elif message_upper.startswith("WARNING"):
|
| return LogLevel.WARNING
|
| elif message_upper.startswith("ERROR"):
|
| return LogLevel.ERROR
|
| else:
|
| return LogLevel.DEFAULT
|
|
|
| def _process_queue(self):
|
| """Process messages from the queue and update the text widget."""
|
| try:
|
| while not self.message_queue.empty():
|
| message = self.message_queue.get_nowait()
|
|
|
|
|
| if message is None:
|
| self.root.quit()
|
| return
|
|
|
|
|
|
|
| current_position = self.text_widget.yview()
|
|
|
| was_at_bottom = current_position[1] > 0.99
|
|
|
| log_level = self._determine_log_level(message)
|
|
|
|
|
| self.text_widget.configure(state=tk.NORMAL)
|
|
|
|
|
| if self.tool_names:
|
|
|
| start_index = self.text_widget.index("end-1c")
|
|
|
|
|
| self.text_widget.insert(tk.END, message + "\n", log_level.name)
|
|
|
|
|
| line, char = map(int, start_index.split("."))
|
|
|
|
|
| for tool_name in self.tool_names:
|
| start_offset = 0
|
| while True:
|
| found_at = message.find(tool_name, start_offset)
|
| if found_at == -1:
|
| break
|
|
|
|
|
| offset_line = line
|
| offset_char = char
|
| for c in message[:found_at]:
|
| if c == "\n":
|
| offset_line += 1
|
| offset_char = 0
|
| else:
|
| offset_char += 1
|
|
|
|
|
| start_pos = f"{offset_line}.{offset_char}"
|
| end_pos = f"{offset_line}.{offset_char + len(tool_name)}"
|
|
|
|
|
| self.text_widget.tag_add("TOOL_NAME", start_pos, end_pos)
|
|
|
| start_offset = found_at + len(tool_name)
|
|
|
| else:
|
|
|
| self.text_widget.insert(tk.END, message + "\n", log_level.name)
|
|
|
| self.text_widget.configure(state=tk.DISABLED)
|
|
|
|
|
| if was_at_bottom:
|
| self.text_widget.see(tk.END)
|
|
|
|
|
| if self.running:
|
| self.root.after(100, self._process_queue)
|
|
|
| except Exception as e:
|
| print(f"Error processing message queue: {e}", file=sys.stderr)
|
| if self.running:
|
| self.root.after(100, self._process_queue)
|
|
|
| def run_gui(self):
|
| """Run the GUI"""
|
| self.running = True
|
| try:
|
|
|
| if sys.platform == "win32":
|
| import ctypes
|
|
|
| ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("oraios.serena")
|
|
|
| self.root = tk.Tk()
|
| self.root.title(self.title)
|
| self.root.geometry(f"{self.width}x{self.height}")
|
|
|
|
|
| self.root.columnconfigure(0, weight=1)
|
|
|
| self.root.rowconfigure(0, weight=0)
|
| self.root.rowconfigure(1, weight=1)
|
|
|
| dashboard_path = Path(constants.SERENA_DASHBOARD_DIR)
|
|
|
|
|
| try:
|
|
|
| image_path = dashboard_path / "serena-logs.png"
|
| self.logo_image = tk.PhotoImage(file=image_path)
|
|
|
|
|
| self.logo_label = tk.Label(self.root, image=self.logo_image)
|
| self.logo_label.grid(row=0, column=0, sticky="ew")
|
| except Exception as e:
|
| print(f"Error loading logo image: {e}", file=sys.stderr)
|
|
|
|
|
| frame = tk.Frame(self.root)
|
| frame.grid(row=1, column=0, sticky="nsew")
|
| frame.columnconfigure(0, weight=1)
|
| frame.rowconfigure(0, weight=1)
|
|
|
|
|
| h_scrollbar = tk.Scrollbar(frame, orient=tk.HORIZONTAL)
|
| h_scrollbar.grid(row=1, column=0, sticky="ew")
|
|
|
|
|
| v_scrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL)
|
| v_scrollbar.grid(row=0, column=1, sticky="ns")
|
|
|
|
|
| self.text_widget = tk.Text(
|
| frame, wrap=tk.NONE, width=self.width, height=self.height, xscrollcommand=h_scrollbar.set, yscrollcommand=v_scrollbar.set
|
| )
|
| self.text_widget.grid(row=0, column=0, sticky="nsew")
|
| self.text_widget.configure(state=tk.DISABLED)
|
|
|
|
|
| h_scrollbar.config(command=self.text_widget.xview)
|
| v_scrollbar.config(command=self.text_widget.yview)
|
|
|
|
|
| for level, color in self.log_colors.items():
|
| self.text_widget.tag_configure(level.name, foreground=color)
|
|
|
|
|
| self.text_widget.tag_configure("TOOL_NAME", background="#ffff00")
|
|
|
|
|
| self.root.after(100, self._process_queue)
|
|
|
|
|
| if self.mode == "dashboard":
|
| self.root.protocol("WM_DELETE_WINDOW", lambda: self.root.iconify())
|
| else:
|
| self.root.protocol("WM_DELETE_WINDOW", self.stop)
|
|
|
|
|
| if self.mode == "dashboard":
|
| menubar = tk.Menu(self.root)
|
| server_menu = tk.Menu(menubar, tearoff=0)
|
| server_menu.add_command(label="Shutdown", command=self._shutdown_server)
|
| menubar.add_cascade(label="Server", menu=server_menu)
|
| self.root.config(menu=menubar)
|
|
|
|
|
| icon_16 = tk.PhotoImage(file=dashboard_path / "serena-icon-16.png")
|
| icon_32 = tk.PhotoImage(file=dashboard_path / "serena-icon-32.png")
|
| icon_48 = tk.PhotoImage(file=dashboard_path / "serena-icon-48.png")
|
| self.root.iconphoto(False, icon_48, icon_32, icon_16)
|
|
|
|
|
| self.root.mainloop()
|
|
|
| except Exception as e:
|
| print(f"Error in GUI thread: {e}", file=sys.stderr)
|
| finally:
|
| self.running = False
|
|
|
| def _shutdown_server(self) -> None:
|
| log.info("Shutting down Serena")
|
|
|
|
|
| os._exit(0)
|
|
|
|
|
| class GuiLogViewerHandler(logging.Handler):
|
| """
|
| A logging handler that sends log records to a ThreadedLogViewer instance.
|
| This handler can be integrated with Python's standard logging module
|
| to direct log entries to a GUI log viewer.
|
| """
|
|
|
| def __init__(
|
| self,
|
| log_viewer: GuiLogViewer,
|
| level=logging.NOTSET,
|
| format_string: str | None = "%(levelname)-5s %(asctime)-15s %(name)s:%(funcName)s:%(lineno)d - %(message)s",
|
| ):
|
| """
|
| Initialize the handler with a ThreadedLogViewer instance.
|
|
|
| Args:
|
| log_viewer: A ThreadedLogViewer instance that will display the logs
|
| level: The logging level (default: NOTSET which captures all logs)
|
| format_string: the format string
|
|
|
| """
|
| super().__init__(level)
|
| self.log_viewer = log_viewer
|
| self.formatter = logging.Formatter(format_string)
|
|
|
|
|
| if not self.log_viewer.running:
|
| self.log_viewer.start()
|
|
|
| @classmethod
|
| def is_instance_registered(cls) -> bool:
|
| for h in logging.Logger.root.handlers:
|
| if isinstance(h, cls):
|
| return True
|
| return False
|
|
|
| def emit(self, record):
|
| """
|
| Emit a log record to the ThreadedLogViewer.
|
|
|
| Args:
|
| record: The log record to emit
|
|
|
| """
|
| try:
|
|
|
| msg = self.format(record)
|
|
|
|
|
| level_prefix = record.levelname
|
|
|
|
|
| if not msg.startswith(level_prefix):
|
| msg = f"{level_prefix}: {msg}"
|
|
|
| self.log_viewer.add_log(msg)
|
|
|
| except Exception:
|
| self.handleError(record)
|
|
|
| def close(self):
|
| """
|
| Close the handler and optionally stop the log viewer.
|
| """
|
|
|
|
|
| super().close()
|
|
|
| def stop_viewer(self):
|
| """
|
| Explicitly stop the associated log viewer.
|
| """
|
| if self.log_viewer.running:
|
| self.log_viewer.stop()
|
|
|
|
|
| def show_fatal_exception(e: Exception):
|
| """
|
| Makes sure the given exception is shown in the GUI log viewer,
|
| either an existing instance or a new one.
|
|
|
| :param e: the exception to display
|
| """
|
|
|
| log_viewer = GuiLogViewer("error")
|
| exc_info = "".join(traceback.format_exception(type(e), e, e.__traceback__))
|
| log_viewer.add_log(f"ERROR Fatal exception: {e}\n{exc_info}")
|
| log_viewer.run_gui()
|
|
|