github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/go-control-plane/pkg/test/v3/accesslog.go (about) 1 package test 2 3 import ( 4 "fmt" 5 "sync" 6 "time" 7 8 alf "github.com/hxx258456/ccgo/go-control-plane/envoy/data/accesslog/v3" 9 accessloggrpc "github.com/hxx258456/ccgo/go-control-plane/envoy/service/accesslog/v3" 10 ) 11 12 // AccessLogService buffers access logs from the remote Envoy nodes. 13 type AccessLogService struct { 14 entries []string 15 mu sync.Mutex 16 } 17 18 func (svc *AccessLogService) log(entry string) { 19 svc.mu.Lock() 20 defer svc.mu.Unlock() 21 svc.entries = append(svc.entries, entry) 22 } 23 24 // Dump releases the collected log entries and clears the log entry list. 25 func (svc *AccessLogService) Dump(f func(string)) { 26 svc.mu.Lock() 27 defer svc.mu.Unlock() 28 for _, entry := range svc.entries { 29 f(entry) 30 } 31 svc.entries = nil 32 } 33 34 // StreamAccessLogs implements the access log service. 35 func (svc *AccessLogService) StreamAccessLogs(stream accessloggrpc.AccessLogService_StreamAccessLogsServer) error { 36 var logName string 37 for { 38 msg, err := stream.Recv() 39 if err != nil { 40 return nil 41 } 42 if msg.Identifier != nil { 43 logName = msg.Identifier.LogName 44 } 45 switch entries := msg.LogEntries.(type) { 46 case *accessloggrpc.StreamAccessLogsMessage_HttpLogs: 47 for _, entry := range entries.HttpLogs.LogEntry { 48 if entry != nil { 49 common := entry.CommonProperties 50 req := entry.Request 51 resp := entry.Response 52 if common == nil { 53 common = &alf.AccessLogCommon{} 54 } 55 if req == nil { 56 req = &alf.HTTPRequestProperties{} 57 } 58 if resp == nil { 59 resp = &alf.HTTPResponseProperties{} 60 } 61 svc.log(fmt.Sprintf("[%s%s] %s %s %s %d %s %s", 62 logName, time.Now().Format(time.RFC3339), req.Authority, req.Path, req.Scheme, 63 resp.ResponseCode.GetValue(), req.RequestId, common.UpstreamCluster)) 64 } 65 } 66 case *accessloggrpc.StreamAccessLogsMessage_TcpLogs: 67 for _, entry := range entries.TcpLogs.LogEntry { 68 if entry != nil { 69 common := entry.CommonProperties 70 if common == nil { 71 common = &alf.AccessLogCommon{} 72 } 73 svc.log(fmt.Sprintf("[%s%s] tcp %s %s", 74 logName, time.Now().Format(time.RFC3339), common.UpstreamLocalAddress, common.UpstreamCluster)) 75 } 76 } 77 } 78 } 79 }