logs_service.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import os
  2. import re
  3. from loguru import logger
  4. ANSI_ESCAPE_RE = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
  5. def _strip_ansi(line):
  6. return ANSI_ESCAPE_RE.sub("", line)
  7. def read_logs(log_files, max_lines, debug=False):
  8. """Read last `max_lines` from each file in `log_files`.
  9. Returns a dict mapping basename -> list-of-lines.
  10. """
  11. logs = {}
  12. for log_file in log_files:
  13. try:
  14. with open(log_file, errors="replace") as f:
  15. lines = f.readlines()
  16. cleaned = [
  17. _strip_ansi(line.rstrip("\n")) for line in lines[-max_lines:]
  18. ]
  19. logs[os.path.basename(log_file)] = cleaned
  20. except FileNotFoundError:
  21. logs[os.path.basename(log_file)] = ["Log file not found"]
  22. except Exception as e:
  23. logger.exception("Error reading log file %s", log_file)
  24. if debug:
  25. logs[os.path.basename(log_file)] = [f"Error reading log: {str(e)}"]
  26. else:
  27. logs[os.path.basename(log_file)] = ["Error reading log"]
  28. return logs