Product Catalog Service
আপনি এই পৃষ্ঠার ইংরেজি সংস্করণ দেখছেন কারণ এটি এখনও সম্পূর্ণভাবে অনুবাদ করা হয়নি। সাহায্য করতে আগ্রহী? দেখুন Contributing।
This service is responsible to return information about products. The service can be used to get all products, search for specific products, or return details about any single product.
Product Catalog service source
OpenTelemetry SDK initialization
The OpenTelemetry SDK is configured manually in code, in the otel.go file. The
initOpenTelemetry function sets the global propagator, builds a shared
resource, and initializes the tracer, meter, and logger providers. It returns a
single function that shuts down all providers.
func initOpenTelemetry(ctx context.Context) (func(context.Context) error, error) {
var shutdownFuncs []func(context.Context) error
shutdown := func(ctx context.Context) error {
var err error
for _, fn := range shutdownFuncs {
err = errors.Join(err, fn(ctx))
}
return err
}
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{},
propagation.Baggage{},
))
res := initResource(ctx)
tp, err := initTracerProvider(ctx, res)
if err != nil {
return shutdown, err
}
shutdownFuncs = append(shutdownFuncs, tp.Shutdown)
mp, err := initMeterProvider(ctx, res)
if err != nil {
return shutdown, err
}
shutdownFuncs = append(shutdownFuncs, mp.Shutdown)
lp, err := initLoggerProvider(ctx, res)
if err != nil {
return shutdown, err
}
shutdownFuncs = append(shutdownFuncs, lp.Shutdown)
return shutdown, nil
}
All exporters use OTLP over HTTP and are configured through the standard
OTEL_EXPORTER_OTLP_* environment variables, so no endpoint or protocol is
hard-coded in the service.
Resource
The resource is built from the OTEL_RESOURCE_ATTRIBUTES and
OTEL_SERVICE_NAME environment variables, together with the telemetry SDK,
container, host, OS, and process resource detectors. The same resource is shared
by all providers.
func initResource(ctx context.Context) *resource.Resource {
res, err := resource.New(ctx,
resource.WithFromEnv(),
resource.WithTelemetrySDK(),
resource.WithContainer(),
resource.WithHost(),
resource.WithOS(),
resource.WithProcess(),
)
if err != nil {
logger.Warn("Built partial OpenTelemetry resource", slog.Any("error", err))
}
if res == nil {
res = resource.Default()
}
return res
}
Shutdown
You should shut down the providers when your service is shut down to ensure all
telemetry is exported. This service calls the shutdown function returned by
initOpenTelemetry as part of a deferred function in main:
shutdownOTel, err := initOpenTelemetry(ctx)
if err != nil {
logger.Error(fmt.Sprintf("Failed to initialize OpenTelemetry SDK: %v", err))
os.Exit(1)
}
defer func() {
if err := shutdownOTel(ctx); err != nil {
logger.Error(fmt.Sprintf("Error shutting down OpenTelemetry SDK: %v", err))
}
logger.Info("Shutdown OpenTelemetry SDK")
}()
Traces
Initializing Tracing
The tracer provider is created by the initTracerProvider function, which uses
an OTLP/HTTP trace exporter with a batching span processor.
func initTracerProvider(ctx context.Context, res *resource.Resource) (*sdktrace.TracerProvider, error) {
exporter, err := otlptracehttp.New(ctx)
if err != nil {
return nil, fmt.Errorf("creating OTLP trace exporter: %w", err)
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exporter),
sdktrace.WithResource(res),
)
otel.SetTracerProvider(tp)
return tp, nil
}
Adding gRPC auto-instrumentation
This service receives gRPC requests, which are instrumented in the main function as part of the gRPC server creation. Health check requests are filtered out so that they don’t generate spans.
srv := grpc.NewServer(
grpc.StatsHandler(otelgrpc.NewServerHandler(
otelgrpc.WithFilter(filters.Not(filters.HealthCheck())),
)),
)
Add attributes to auto-instrumented spans
Within the execution of auto-instrumented code you can get current span from context.
span := trace.SpanFromContext(ctx)
Adding attributes to a span is accomplished using SetAttributes on the span
object. In the GetProduct function an attribute for the product ID is added to
the span.
span.SetAttributes(
attribute.String("demo.product.id", req.Id),
)
Setting span status
This service can catch and handle an error condition based on a feature flag. In
an error condition, the span status is set accordingly using SetStatus on the
span object. You can see this in the GetProduct function.
msg := fmt.Sprintf("failed to query product: %v", dbErr)
span.SetStatus(otelcodes.Error, msg)
Add span events
Adding span events is accomplished using AddEvent on the span object. In the
GetProduct function a span event is added when an error condition is handled,
or when a product is successfully found.
span.AddEvent(msg)
Metrics
Initializing Metrics
The meter provider is created by the initMeterProvider function, which uses an
OTLP/HTTP metric exporter with a periodic reader.
func initMeterProvider(ctx context.Context, res *resource.Resource) (*sdkmetric.MeterProvider, error) {
exporter, err := otlpmetrichttp.New(ctx)
if err != nil {
return nil, fmt.Errorf("creating OTLP metric exporter: %w", err)
}
mp := sdkmetric.NewMeterProvider(
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(exporter)),
sdkmetric.WithResource(res),
)
otel.SetMeterProvider(mp)
return mp, nil
}
Metric temporality and the default histogram aggregation can be set through the
OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE and
OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION environment
variables.
Adding golang runtime auto-instrumentation
Golang runtime is instrumented in the main function
err = runtime.Start(runtime.WithMinimumReadMemStatsInterval(time.Second))
if err != nil {
logger.Error(err.Error())
}
Logs
You can send your logs to the OpenTelemetry Collector in two ways:
- Directly to the Collector
- Through a file or
stdout
You can find documentation specifying how to use both these approaches in the Logs section of the Manual Instrumentation documentation.
The Product Catalog service sends the logs directly to the Collector, and uses a
log bridge to send its logs, bridging to the slog logging package, which
outputs structured logs.
LoggerProvider initialization
The logger provider is created by the initLoggerProvider function, which uses
an OTLP/HTTP log exporter with a batching log record processor.
func initLoggerProvider(ctx context.Context, res *resource.Resource) (*sdklog.LoggerProvider, error) {
exporter, err := otlploghttp.New(ctx)
if err != nil {
return nil, fmt.Errorf("creating OTLP log exporter: %w", err)
}
lp := sdklog.NewLoggerProvider(
sdklog.WithProcessor(sdklog.NewBatchProcessor(exporter)),
sdklog.WithResource(res),
)
global.SetLoggerProvider(lp)
return lp, nil
}
Logging functionality
This service sends logs to the Collector using the log bridge for the slog
package. The logs are output in a structured format.
First, initialize the logger:
var logger *slog.Logger
func init() {
logger = otelslog.NewLogger("product-catalog")
}
Note the use of fmt.Sprintf to format the output before it’s sent to the
logger:
logger.Info(fmt.Sprintf("Product Catalog gRPC server started on port: %s", port))
logger.Error(fmt.Sprintf("Error shutting down OpenTelemetry SDK: %v", err))
The advantage of using slog is the ability to attach additional attributes to
the output. The following example attaches the demo.product.name and
demo.product.id attributes. This makes it possible to view and parse these as
part of the log output and makes it easier to view them as separate columns in
Grafana:
logger.LogAttrs(
ctx,
slog.LevelInfo, fmt.Sprintf("Product found: %s (%s) in %d ms", found.Name, req.Id, elapsed.Milliseconds()),
slog.String("demo.product.name", found.Name),
slog.String("demo.product.id", req.Id),
)
মূল্যায়ন
এই পৃষ্ঠাটি কি সহায়ক ছিল?
Thank you. Your feedback is appreciated!
Please let us know how we can improve this page. Your feedback is appreciated!