micro/debug/service/service.go

89 lines
1.6 KiB
Go
Raw Normal View History

2019-12-17 18:38:03 +03:00
// Package service provides the service log
package service
import (
"context"
"fmt"
"time"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/debug/log"
2019-12-04 15:27:30 +03:00
pb "github.com/micro/go-micro/debug/service/proto"
)
// Debug provides debug service client
2019-12-17 18:38:03 +03:00
type debugClient struct {
Client pb.DebugService
}
2019-12-17 18:56:49 +03:00
// NewClient provides a debug client
func NewClient(name string) *debugClient {
// create default client
cli := client.DefaultClient
2019-12-17 18:38:03 +03:00
return &debugClient{
Client: pb.NewDebugService(name, cli),
}
}
2019-12-17 19:56:55 +03:00
// Logs queries the services logs and returns a channel to read the logs from
func (d *debugClient) Log(since time.Time, count int, stream bool) (log.Stream, error) {
req := &pb.LogRequest{}
2019-12-17 19:56:55 +03:00
if !since.IsZero() {
req.Since = since.Unix()
}
2019-12-17 19:56:55 +03:00
if count > 0 {
req.Count = int64(count)
}
2019-12-17 19:56:55 +03:00
// set whether to stream
req.Stream = stream
// get the log stream
2019-12-17 19:56:55 +03:00
serverStream, err := d.Client.Log(context.Background(), req)
if err != nil {
return nil, fmt.Errorf("failed getting log stream: %s", err)
}
2019-12-17 19:56:55 +03:00
lg := &logStream{
stream: make(chan log.Record),
stop: make(chan bool),
}
2019-12-17 18:38:03 +03:00
// go stream logs
2019-12-17 19:56:55 +03:00
go d.streamLogs(lg, serverStream)
2019-12-17 19:56:55 +03:00
return lg, nil
}
2019-12-17 19:56:55 +03:00
func (d *debugClient) streamLogs(lg *logStream, stream pb.Debug_LogService) {
defer stream.Close()
2019-12-17 19:56:55 +03:00
defer lg.Stop()
for {
resp, err := stream.Recv()
if err != nil {
break
}
metadata := make(map[string]string)
for k, v := range resp.Metadata {
metadata[k] = v
}
record := log.Record{
Timestamp: time.Unix(resp.Timestamp, 0),
Value: resp.Value,
Metadata: metadata,
}
2019-12-17 19:56:55 +03:00
select {
case <-lg.stop:
return
case lg.stream <- record:
}
}
}