log.go 998 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package libbox
  2. import (
  3. "bufio"
  4. "log"
  5. "os"
  6. )
  7. type StandardOutput interface {
  8. WriteOutput(message string)
  9. WriteErrorOutput(message string)
  10. }
  11. func SetOutput(output StandardOutput) {
  12. log.SetOutput(logWriter{output})
  13. pipeIn, pipeOut, err := os.Pipe()
  14. if err != nil {
  15. panic(err)
  16. }
  17. os.Stdout = os.NewFile(pipeOut.Fd(), "stdout")
  18. go lineLog(pipeIn, output.WriteOutput)
  19. pipeIn, pipeOut, err = os.Pipe()
  20. if err != nil {
  21. panic(err)
  22. }
  23. os.Stderr = os.NewFile(pipeOut.Fd(), "srderr")
  24. go lineLog(pipeIn, output.WriteErrorOutput)
  25. }
  26. type logWriter struct {
  27. output StandardOutput
  28. }
  29. func (w logWriter) Write(p []byte) (n int, err error) {
  30. w.output.WriteOutput(string(p))
  31. return len(p), nil
  32. }
  33. func lineLog(f *os.File, output func(string)) {
  34. const logSize = 1024 // matches android/log.h.
  35. r := bufio.NewReaderSize(f, logSize)
  36. for {
  37. line, _, err := r.ReadLine()
  38. str := string(line)
  39. if err != nil {
  40. str += " " + err.Error()
  41. }
  42. output(str)
  43. if err != nil {
  44. break
  45. }
  46. }
  47. }