-
Notifications
You must be signed in to change notification settings - Fork 0
/
youlog_service_engine.go
82 lines (74 loc) · 1.82 KB
/
youlog_service_engine.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
71
72
73
74
75
76
77
78
79
80
81
82
package youlog
import (
"context"
"encoding/json"
"errors"
grpcpool "github.com/processout/grpc-go-pool"
"github.com/project-xpolaris/youplustoolkit/youlog/logservice"
"google.golang.org/grpc"
"time"
)
type YouLogServiceEngineConfig struct {
Address string `mapstructure:"address"`
}
type YouLogEngine struct {
client *YouLogClient
Config *YouLogServiceEngineConfig
}
func (e *YouLogEngine) Init() error {
e.client = NewYouLogClient(e.Config.Address)
return e.client.Init()
}
func (e *YouLogEngine) WriteLog(context context.Context, scope *Scope, message string, level int64) error {
client, err := e.client.GetClient()
if err != nil {
return err
}
extra, err := json.Marshal(scope.Fields)
if err != nil {
return err
}
data := &logservice.LogData{
Application: scope.LogClient.Application,
Instance: scope.LogClient.Instance,
Scope: scope.Name,
Extra: string(extra),
Message: message,
Level: level,
Time: time.Now().UnixMilli(),
}
reply, err := client.WriteLog(context, data)
if err != nil {
return err
}
if reply.Success == false {
return errors.New("service error")
}
return nil
}
type YouLogClient struct {
Address string
pool *grpcpool.Pool
}
func NewYouLogClient(address string) *YouLogClient {
return &YouLogClient{Address: address}
}
func (c *YouLogClient) Init() error {
var factory grpcpool.Factory = func() (*grpc.ClientConn, error) {
return grpc.DialContext(context.Background(), c.Address, grpc.WithInsecure())
}
pool, err := grpcpool.New(factory, 1, 3, 0)
if err != nil {
return err
}
c.pool = pool
return nil
}
func (c *YouLogClient) GetClient() (logservice.LogServiceClient, error) {
conn, err := c.pool.Get(context.Background())
if err != nil {
return nil, err
}
client := logservice.NewLogServiceClient(conn)
return client, nil
}