log_ios.go 980 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // SPDX-License-Identifier: Unlicense OR MIT
  2. //go:build darwin && ios
  3. // +build darwin,ios
  4. package app
  5. /*
  6. #cgo CFLAGS: -Werror -fmodules -fobjc-arc -x objective-c
  7. @import Foundation;
  8. static void nslog(char *str) {
  9. NSLog(@"%@", @(str));
  10. }
  11. */
  12. import "C"
  13. import (
  14. "bufio"
  15. "io"
  16. "log"
  17. "unsafe"
  18. _ "gioui.org/internal/cocoainit"
  19. )
  20. func init() {
  21. // macOS Console already includes timestamps.
  22. log.SetFlags(log.Flags() &^ log.LstdFlags)
  23. log.SetOutput(newNSLogWriter())
  24. }
  25. func newNSLogWriter() io.Writer {
  26. r, w := io.Pipe()
  27. go func() {
  28. // 1024 is an arbitrary truncation limit, taken from Android's
  29. // log buffer size.
  30. lineBuf := bufio.NewReaderSize(r, 1024)
  31. // The buffer to pass to C, including the terminating '\0'.
  32. buf := make([]byte, lineBuf.Size()+1)
  33. cbuf := (*C.char)(unsafe.Pointer(&buf[0]))
  34. for {
  35. line, _, err := lineBuf.ReadLine()
  36. if err != nil {
  37. break
  38. }
  39. copy(buf, line)
  40. buf[len(line)] = 0
  41. C.nslog(cbuf)
  42. }
  43. }()
  44. return w
  45. }