gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/debug/service/service.go (about) 1 package service 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "gitee.com/liuxuezhan/go-micro-v1.18.0/client" 9 10 "gitee.com/liuxuezhan/go-micro-v1.18.0/debug/log" 11 pb "gitee.com/liuxuezhan/go-micro-v1.18.0/debug/service/proto" 12 ) 13 14 // Debug provides debug service client 15 type Debug struct { 16 dbg pb.DebugService 17 } 18 19 // NewDebug provides Debug service implementation 20 func NewDebug(name string) *Debug { 21 // create default client 22 cli := client.DefaultClient 23 24 return &Debug{ 25 dbg: pb.NewDebugService(name, cli), 26 } 27 } 28 29 // Logs queries the service logs and returns a channel to read the logs from 30 func (d *Debug) Log(opts ...log.ReadOption) (<-chan log.Record, error) { 31 options := log.ReadOptions{} 32 // initialize the read options 33 for _, o := range opts { 34 o(&options) 35 } 36 37 req := &pb.LogRequest{} 38 if !options.Since.IsZero() { 39 req.Since = options.Since.Unix() 40 } 41 42 if options.Count > 0 { 43 req.Count = int64(options.Count) 44 } 45 46 req.Stream = options.Stream 47 48 // get the log stream 49 stream, err := d.dbg.Log(context.Background(), req) 50 if err != nil { 51 return nil, fmt.Errorf("failed getting log stream: %s", err) 52 } 53 54 // log channel for streaming logs 55 logChan := make(chan log.Record) 56 // go stream logs 57 go d.streamLogs(logChan, stream) 58 59 return logChan, nil 60 } 61 62 func (d *Debug) streamLogs(logChan chan log.Record, stream pb.Debug_LogService) { 63 defer stream.Close() 64 65 for { 66 resp, err := stream.Recv() 67 if err != nil { 68 break 69 } 70 71 metadata := make(map[string]string) 72 for k, v := range resp.Metadata { 73 metadata[k] = v 74 } 75 76 record := log.Record{ 77 Timestamp: time.Unix(resp.Timestamp, 0), 78 Value: resp.Value, 79 Metadata: metadata, 80 } 81 82 logChan <- record 83 } 84 85 close(logChan) 86 }