stderr_windows.go 802 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. //go:build windows
  2. package util
  3. import (
  4. "log"
  5. "os"
  6. "syscall"
  7. )
  8. var (
  9. kernel32 = syscall.MustLoadDLL("kernel32.dll")
  10. procSetStdHandle = kernel32.MustFindProc("SetStdHandle")
  11. )
  12. func setStdHandle(stdhandle int32, handle syscall.Handle) error {
  13. r0, _, e1 := syscall.Syscall(procSetStdHandle.Addr(), 2, uintptr(stdhandle), uintptr(handle), 0)
  14. if r0 == 0 {
  15. if e1 != 0 {
  16. return error(e1)
  17. }
  18. return syscall.EINVAL
  19. }
  20. return nil
  21. }
  22. // redirectStderr to the file passed in
  23. func init() {
  24. logFile := initFatalLog()
  25. if logFile != nil {
  26. err := setStdHandle(syscall.STD_ERROR_HANDLE, syscall.Handle(logFile.Fd()))
  27. if err != nil {
  28. log.Fatalf("Failed to redirect stderr to file: %v", err)
  29. }
  30. // SetStdHandle does not affect prior references to stderr
  31. os.Stderr = logFile
  32. }
  33. }