Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature(trace): add context to Logger API #20

Open
wants to merge 28 commits into
base: main
Choose a base branch
from

Conversation

1046102779
Copy link
Member

@1046102779 1046102779 commented Sep 6, 2022

Signed-off-by: 1046102779 [email protected]

Description

At present, our servers need to correlate logs and traces.

This is a very urgent matter, I hope everyone can review these code at quickly. Thanks.

Checklist

Please make sure you've completed the relevant tasks for this PR, out of the following list:

  • Logger API with context.
  • Support Opentelemetry.
  • Unit tests.

/cc @pkedy @yaron2 @artursouza @daixiang0 @berndverst @ItalyPaleAle

@1046102779 1046102779 requested a review from a team as a code owner September 6, 2022 08:04
@1046102779
Copy link
Member Author

Add package trace to associate micrologic and dapr runtime. as follows:

  1. service type: client && server,
  2. protocol type: http && gRPC

gRPC client(go-sdk):

// NewClientWithAddress instantiates Dapr using specific address (including port).
func NewClientWithAddress(address string) (client cc.Client, err error) {
	if address == "" {
		return nil, errors.New("nil address")
	}
	logger.Printf("dapr client initializing for: %s", address)

	ctx, ctxCancel := context.WithTimeout(context.Background(), 1*time.Second)
	conn, err := grpc.DialContext(
		ctx,
		address,
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithBlock(),
		grpc.WithUnaryInterceptor(trace.GRPCClientUnaryInterceptor),
		grpc.WithStreamInterceptor(trace.GRPCClientStreamInterceptor),
	)
	if err != nil {
		ctxCancel()
		return nil, errors.Wrapf(err, "error creating connection to '%s': %v", address, err)
	}
	if hasToken := os.Getenv(apiTokenEnvVarName); hasToken != "" {
		logger.Println("client uses API token")
	}

	return newClientWithConnectionAndCancelFunc(conn, ctxCancel), nil
}

gRPC server(go-sdk):

// Start registers the server and starts it.
func (s *Server) Start() error {
	gs := grpc.NewServer(
		grpc.UnaryInterceptor(trace.GRPCServerUnaryInterceptor),
		grpc.StreamInterceptor(trace.GRPCServerStreamInterceptor),
	)
	runtimepbv1.RegisterAppCallbackServer(gs, s)
	s.grpcServer = gs
	return gs.Serve(s.listener)
}

@1046102779
Copy link
Member Author

1046102779 commented Sep 7, 2022

/cc @yaron2

We desperately need this Logger Context API feature.

ps. It seems that this repo is not maintained anymore, can I be the maintainer of this repo? Currently feedback is slow for issues and PRs .

@berndverst
Copy link
Member

/cc @yaron2

We desperately need this Logger Context API feature.

ps. It seems that this repo is not maintained anymore, can I be the maintainer of this repo? Currently feedback is slow for issues and PRs .

This repo is maintained, but it does not frequently require changes. In a way, it is controlled by Dapr runtime maintainers.

trace/trace.go Outdated Show resolved Hide resolved
trace/adapter.go Outdated Show resolved Hide resolved
@codecov-commenter
Copy link

codecov-commenter commented Sep 7, 2022

Codecov Report

Merging #20 (b91bb22) into main (fcb0995) will decrease coverage by 4.29%.
The diff coverage is 63.19%.

@@            Coverage Diff             @@
##             main      #20      +/-   ##
==========================================
- Coverage   90.46%   86.17%   -4.29%     
==========================================
  Files          18       22       +4     
  Lines         891     1049     +158     
==========================================
+ Hits          806      904      +98     
- Misses         72      116      +44     
- Partials       13       29      +16     
Impacted Files Coverage Δ
logger/logger.go 100.00% <ø> (ø)
logger/nop_logger.go 0.00% <0.00%> (ø)
trace/trace.go 50.00% <50.00%> (ø)
trace/adapter.go 60.52% <60.52%> (ø)
trace/span_context.go 61.11% <61.11%> (ø)
trace/id_generator.go 78.26% <78.26%> (ø)
logger/dapr_logger.go 96.82% <100.00%> (+0.74%) ⬆️
logger/options.go 82.35% <100.00%> (+1.70%) ⬆️

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

@1046102779
Copy link
Member Author

1046102779 commented Sep 7, 2022

id(traceid): 196d92cb7ed0571d7129a803cba99bed

➜  logger git:(feature/log0905) go test -v ./... -test.run=TestJSONLoggerFieldsWithSpanCo
ntext
=== RUN   TestJSONLoggerFieldsWithSpanContext
=== RUN   TestJSONLoggerFieldsWithSpanContext/info()
line: {"app_id":"dapr_app","instance":"dapr-pod","level":"info","msg":"King Dapr","scope":"fakeLogger","time":"2022-09-07T10:34:58.008556446+08:00","type":"log","ver":"unknown"}
=== RUN   TestJSONLoggerFieldsWithSpanContext/info()#01
line: {"app_id":"dapr_app","id":"196d92cb7ed0571d7129a803cba99bed","instance":"dapr-pod","level":"info","msg":"King Dapr","scope":"fakeLogger","time":"2022-09-07T10:34:58.008773554+08:00","type":"log","ver":"dapr_app"}
--- PASS: TestJSONLoggerFieldsWithSpanContext (0.00s)
    --- PASS: TestJSONLoggerFieldsWithSpanContext/info() (0.00s)
    --- PASS: TestJSONLoggerFieldsWithSpanContext/info()#01 (0.00s)
PASS
ok      github.com/dapr/kit/logger      0.006s

@1046102779
Copy link
Member Author

/cc @daixiang0 @artursouza @yaron2 @pkedy

@1046102779
Copy link
Member Author

1 similar comment
@1046102779
Copy link
Member Author

@yaron2
Copy link
Member

yaron2 commented Sep 16, 2022

@daixiang0 @berndverst can you complete the review here?

go.mod Outdated Show resolved Hide resolved
@1046102779
Copy link
Member Author

cc @yaron2 @artursouza @ItalyPaleAle

logger/dapr_logger.go Outdated Show resolved Hide resolved
trace/adapter.go Show resolved Hide resolved
@1046102779
Copy link
Member Author

cc @ItalyPaleAle

@1046102779
Copy link
Member Author

cc @ItalyPaleAle @yaron2 @berndverst

@1046102779
Copy link
Member Author

@1046102779
Copy link
Member Author

@1046102779
Copy link
Member Author

I need this pr to apply micrologic.

@ItalyPaleAle
Copy link
Contributor

@1046102779 Please do not ping maintainers every day.

As for this PR, I still am not clear exactly what this is for. I am also concerned with importing an entire tracing package (and dependencies on things like OTEL) in dapr/kit.

Can you help me understand why this is necessary? How will this be used in Dapr?

@yaron2
Copy link
Member

yaron2 commented Dec 20, 2022

@1046102779 Please do not ping maintainers every day.

As for this PR, I still am not clear exactly what this is for. I am also concerned with importing an entire tracing package (and dependencies on things like OTEL) in dapr/kit.

Can you help me understand why this is necessary? How will this be used in Dapr?

@ItalyPaleAle as discussed, this is to add a trace id if present to the log output to help in correlating service calls with logs.

@1046102779
Copy link
Member Author

(MicroLogic, Dapr runtime)'s trace and log can be associated, and the effect is as follows:

mmexport1671580042227


if id != "" {
return l.WithFields(map[string]any{
"id": id,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we find a better name than id? How about traceId? Anything with the word "trace" in it


// SpanContextGrpc gets span context from grpc request.
func SpanContextFromGrpc(ctx context.Context) trace.SpanContext {
md, ok := metadata.FromIncomingContext(ctx)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method does a lot of re-allocations and string transformations on every call, and it's very slow. Not what we should use with a logger.... I changed it in the runtime to cache the values: https://github.com/dapr/dapr/blob/master/pkg/grpc/metadata/metadata.go

Perhaps consider moving that package (pkg/grpc/metadata) into dapr/kit, and use the FromIncomingContext method from that package.

@@ -0,0 +1,146 @@
package trace
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A lot of this code seems to be available here almost exactly the same: https://github.com/dapr/dapr/blob/master/pkg/diagnostics/tracing.go

Can you perhaps move that package into dapr/kit and consolidate?

@ItalyPaleAle
Copy link
Contributor

Ok makes sense now.

My concern with code duplication remains. A lot of the code here seems to be present in dapr/dapr too, and it would cause duplications.

Can you (maybe in a separate PR first) move some of that code from dapr/dapr into dapr/kit, and then use those packages in both dapr/kit and dapr/dapr?

@1046102779
Copy link
Member Author

Ok makes sense now.

My concern with code duplication remains. A lot of the code here seems to be present in dapr/dapr too, and it would cause duplications.

Can you (maybe in a separate PR first) move some of that code from dapr/dapr into dapr/kit, and then use those packages in both dapr/kit and dapr/dapr?

Yes. I plan to move some trace-related packages in the dapr/dapr main repo to this dapr/kit repo, as a public component capability for dapr/dapr, dapr/go-sdk or MicroLogic.

daixiang0
daixiang0 previously approved these changes Jan 3, 2023
@yaron2
Copy link
Member

yaron2 commented Jan 24, 2023

@1046102779 please resolve the conflicts.

@1046102779
Copy link
Member Author

@1046102779 please resolve the conflicts.

Done.

@daixiang0
Copy link
Member

LGTM

"context"
crand "crypto/rand"
"encoding/binary"
"math/rand"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't use math/rand. Please use a CSPRNG for all sources of random data

trace/trace.go Outdated
// w3c reference: https://www.w3.org/TR/trace-context/#traceparent-header.
// traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01.
// SpanContextFromW3CString generates span context by traceparent.
func SpanContextFromW3CString(traceparent string) trace.SpanContext {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}

// SpanContextFromHTTP get span context from http request.
func SpanContextFromHTTP(h http.Header) trace.SpanContext {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We will also need an adapter for fasthttp if you plan to use that with Dapr?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants