logging_utils.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import sys
  2. from ray._private.utils import open_log
  3. from ray._raylet import StreamRedirector
  4. def redirect_stdout_stderr_if_needed(
  5. stdout_filepath: str,
  6. stderr_filepath: str,
  7. rotation_bytes: int,
  8. rotation_backup_count: int,
  9. ):
  10. """This function sets up redirection for stdout and stderr if needed, based on the given rotation parameters.
  11. params:
  12. stdout_filepath: the filepath stdout will be redirected to; if empty, stdout will not be redirected.
  13. stderr_filepath: the filepath stderr will be redirected to; if empty, stderr will not be redirected.
  14. rotation_bytes: number of bytes which triggers file rotation.
  15. rotation_backup_count: the max size of rotation files.
  16. """
  17. # Setup redirection for stdout and stderr.
  18. if stdout_filepath:
  19. StreamRedirector.redirect_stdout(
  20. stdout_filepath,
  21. rotation_bytes,
  22. rotation_backup_count,
  23. False, # tee_to_stdout
  24. False, # tee_to_stderr
  25. )
  26. if stderr_filepath:
  27. StreamRedirector.redirect_stderr(
  28. stderr_filepath,
  29. rotation_bytes,
  30. rotation_backup_count,
  31. False, # tee_to_stdout
  32. False, # tee_to_stderr
  33. )
  34. # Setup python system stdout/stderr.
  35. stdout_fileno = sys.stdout.fileno()
  36. stderr_fileno = sys.stderr.fileno()
  37. # We also manually set sys.stdout and sys.stderr because that seems to
  38. # have an effect on the output buffering. Without doing this, stdout
  39. # and stderr are heavily buffered resulting in seemingly lost logging
  40. # statements. We never want to close the stdout file descriptor, dup2 will
  41. # close it when necessary and we don't want python's GC to close it.
  42. sys.stdout = open_log(stdout_fileno, unbuffered=True, closefd=False)
  43. sys.stderr = open_log(stderr_fileno, unbuffered=True, closefd=False)