log.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //go:build darwin || linux
  2. package libbox
  3. import (
  4. "os"
  5. "golang.org/x/sys/unix"
  6. )
  7. var stderrFile *os.File
  8. func RedirectStderr(path string) error {
  9. if stats, err := os.Stat(path); err == nil && stats.Size() > 0 {
  10. _ = os.Rename(path, path+".old")
  11. }
  12. outputFile, err := os.Create(path)
  13. if err != nil {
  14. return err
  15. }
  16. err = unix.Dup2(int(outputFile.Fd()), int(os.Stderr.Fd()))
  17. if err != nil {
  18. outputFile.Close()
  19. os.Remove(outputFile.Name())
  20. return err
  21. }
  22. stderrFile = outputFile
  23. return nil
  24. }
  25. func RedirectStderrAsUser(path string, uid, gid int) error {
  26. if stats, err := os.Stat(path); err == nil && stats.Size() > 0 {
  27. _ = os.Rename(path, path+".old")
  28. }
  29. outputFile, err := os.Create(path)
  30. if err != nil {
  31. return err
  32. }
  33. err = outputFile.Chown(uid, gid)
  34. if err != nil {
  35. outputFile.Close()
  36. os.Remove(outputFile.Name())
  37. return err
  38. }
  39. err = unix.Dup2(int(outputFile.Fd()), int(os.Stderr.Fd()))
  40. if err != nil {
  41. outputFile.Close()
  42. os.Remove(outputFile.Name())
  43. return err
  44. }
  45. stderrFile = outputFile
  46. return nil
  47. }