go-kratos / kratos

Your ultimate Go microservices framework for the cloud-native era.
https://go-kratos.dev
MIT License
23.41k stars 4.01k forks source link

feat: tracing add custom report err func #3370

Open lawlielt opened 4 months ago

lawlielt commented 4 months ago

Description (what this PR does / why we need it):

By default, when an error occurs, the following action is taken:

span.RecordError(err)
if e := errors.FromError(err); e != nil {
    span.SetAttributes(attribute.Key("rpc.status_code").Int64(int64(e.Code)))
}

The exception.type in RecordError is the type of the error, which doesn't contain much information. To collect more details, we can customize the action and add new attributes.

Here is an example of how to customize error handling and collect more information:

var (
    errCode int32
)

if st, ok := status.FromError(err); ok {
    errCode = int32(st.Code())
} else {
    errCode = 0
}

span.AddEvent("exception", otelTrace.WithAttributes(
    attribute.Key("exception.type").String(fmt.Sprintf("%T", err)),
    attribute.Key("exception.message").String(err.Error()),
))
span.SetAttributes(attribute.Key("rpc.grpc.status_code").Int64(int64(errCode)))

By doing this, we can collect and record more detailed error information, which helps in better monitoring and debugging of the application.

Which issue(s) this PR fixes (resolves / be part of):

Other special notes for the reviewers:

the default grpc error code in opentelmetry library is rpc.grpc.status_code not rpc.status_code, we can use the custom method to compatible that