-
Notifications
You must be signed in to change notification settings - Fork 2
/
log_android.go
70 lines (60 loc) · 1.52 KB
/
log_android.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build android
package jni
import (
"bufio"
"log"
"os"
"unsafe"
)
// #include <android/log.h>
// #include <stdlib.h>
// #cgo LDFLAGS: -llog
import "C"
var ctag *C.char = C.CString("GoLog")
func init() {
log.SetOutput(&androidWriter{})
r, w, err := os.Pipe()
if err != nil {
panic(err)
}
os.Stderr = w
go lineLog(r, "STDERR", C.ANDROID_LOG_ERROR)
r, w, err = os.Pipe()
if err != nil {
panic(err)
}
os.Stdout = w
go lineLog(r, "STDOUT", C.ANDROID_LOG_INFO)
}
// androidWriter is used for diverting Go 'log' package output to android's INFO log.
type androidWriter struct{}
func (aw *androidWriter) Write(p []byte) (n int, err error) {
cstr := C.CString(string(p))
C.__android_log_write(C.ANDROID_LOG_INFO, ctag, cstr)
C.free(unsafe.Pointer(cstr))
return len(p), nil
}
// lineLog is used for diverting Go Stderr and Stdout to android's logs.
// NOTE(spetrovic): lifted from https://github.com/golang/mobile.
func lineLog(f *os.File, tag string, severity C.int) {
ctag := C.CString(tag)
defer C.free(unsafe.Pointer(ctag))
const logSize = 1024 // matches android/log.h.
r := bufio.NewReaderSize(f, logSize)
for {
line, _, err := r.ReadLine()
str := string(line)
if err != nil {
str += " " + err.Error()
}
cstr := C.CString(str)
C.__android_log_write(severity, ctag, cstr)
C.free(unsafe.Pointer(cstr))
if err != nil {
break
}
}
}