github.com/cybriq/giocore@v0.0.7-0.20210703034601-cfb9cb5f3900/app/internal/log/log_ios.go (about)

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