如何以最简单的方式在Golang中生成X-Amzn-Trace-Id?

huangapple go评论88阅读模式
英文:

how to generate X-Amzn-Trace-Id for Golang in the simplest way

问题

我一直在查看这个亚马逊云服务(AWS)的文档

有没有简单的方法可以使用X-Ray生成“X-Amzn-Trace-Id”?func NewIDGenerator()函数不会生成“Root xxx”格式。

或者我们可以使用一个可信的库吗?谢谢。

英文:

I have been seeing this documentation by AWS

Is there any simple way to generate "X-Amzn-Trace-Id" with X-Ray?
the func NewIDGenerator() doesn't produce the format of Root xxx.

or can we just use a trusted library for it? Thank you

答案1

得分: 2

首先,使用OpenTelemetry的跟踪器创建一个跟踪(Trace),然后将该上下文(context)注入到XRAY传播器(Propagator)中,以根据AWS的ID规范获取TraceId。

func GetAmazonTraceId(ctx context.Context) string {
    propogator := xray.Propagator{}
    carrier := propagation.HeaderCarrier{}
    propogator.Inject(ctx, carrier)
    traceId := carrier.Get("X-Amzn-Trace-Id")
    return traceId
}
英文:

First Create a Trace using OpenTelemetry's tracer and then inject that context to XRAY Propagator to get TraceId as per AWS's ID specification.

func GetAmazonTraceId(ctx context.Context) string {
	propogator := xray.Propagator{}
	carrier := propagation.HeaderCarrier{}
	propogator.Inject(ctx, carrier)
	traceId := carrier.Get("X-Amzn-Trace-Id")
	return traceId
}

答案2

得分: 0

或者,您可以编写代码将标准跟踪ID(字符串)转换为X-Ray跟踪ID。

private static final String TRACE_ID_VERSION = "1";
private static final char TRACE_ID_DELIMITER = '-';
private static final int TRACE_ID_DELIMITER_INDEX_1 = 1;
private static final int TRACE_ID_DELIMITER_INDEX_2 = 10;
private static final int TRACE_ID_FIRST_PART_LENGTH = 8;

public static String toXRayTraceId(String traceId) {
    return TRACE_ID_VERSION
        + TRACE_ID_DELIMITER
        + traceId.substring(0, TRACE_ID_FIRST_PART_LENGTH)
        + TRACE_ID_DELIMITER
        + traceId.substring(TRACE_ID_FIRST_PART_LENGTH);
}

以上是将标准跟踪ID转换为X-Ray跟踪ID的代码。

英文:

Or, you can write your code to convert standard trace id(String) to xray trace id.

private static final String TRACE_ID_VERSION = "1";
private static final char TRACE_ID_DELIMITER = '-';
private static final int TRACE_ID_DELIMITER_INDEX_1 = 1;
private static final int TRACE_ID_DELIMITER_INDEX_2 = 10;
private static final int TRACE_ID_FIRST_PART_LENGTH = 8;

public static String toXRayTraceId(String traceId) {
    return TRACE_ID_VERSION
        + TRACE_ID_DELIMITER
        + traceId.substring(0, TRACE_ID_FIRST_PART_LENGTH)
        + TRACE_ID_DELIMITER
        + traceId.substring(TRACE_ID_FIRST_PART_LENGTH);
  }

huangapple
  • 本文由 发表于 2022年2月22日 10:24:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/71215220.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定