Skip to content

Commit fee7787

Browse files
author
Dmitry Sinyavskiy
committed
feat(grpc, tracing): added datadog trace and log connctor for logrus (grpc interceptor)
1 parent 6cf0dfa commit fee7787

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package datadog
2+
3+
import (
4+
"context"
5+
6+
"github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus"
7+
"github.com/sirupsen/logrus"
8+
"google.golang.org/grpc"
9+
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
10+
)
11+
12+
// LogrusDDTraceContextInjector adds dd.trace_id, dd.span_id as logrus entry fields and puts new log entry into the context. Other interceptors can pick the log entry with ctxlogrus.Extract and add extra data. This interceptor must be used after grpctrace.UnaryServerInterceptor (from "gopkg.in/DataDog/dd-trace-go.v1/contrib/google.golang.org/grpc") and before grpc_logrus.UnaryServerInterceptor (from github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus)
13+
//
14+
// Example:
15+
// ddtracer.Start()
16+
// defer ddtracer.Flush()
17+
// l := logrus.New()
18+
// l.Out = os.Stderr
19+
// logger := logrus.NewEntry(l)
20+
// server := grpctest.NewServer(grpc_middleware.WithUnaryServerChain(
21+
// grpctrace.UnaryServerInterceptor(),
22+
// grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
23+
// midleware.LogrusDDTraceContextInjector(logger),
24+
// grpc_logrus.UnaryServerInterceptor(logger),
25+
// ))
26+
func LogrusDDTraceContextInjector(entry *logrus.Entry) grpc.UnaryServerInterceptor {
27+
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
28+
if span, exists := tracer.SpanFromContext(ctx); exists && span.Context().TraceID() != 0 {
29+
callLog := entry.WithFields(
30+
logrus.Fields{
31+
"dd.trace_id": span.Context().TraceID(),
32+
"dd.span_id": span.Context().SpanID(),
33+
})
34+
callLog = callLog.WithFields(ctxlogrus.Extract(ctx).Data)
35+
ctx = ctxlogrus.ToContext(ctx, callLog)
36+
}
37+
38+
return handler(ctx, req)
39+
}
40+
}

0 commit comments

Comments
 (0)