admin管理员组

文章数量:1122832

According to docs, a meterProvider is essential to build instruments, and that's clear to me. Right after the initializing example of metric initialization, we have the topic aquiring a meter with this object.

Following this implementation in my tests i was note able to properly use meterProvider outside of the package where it's implemented (a package created to hold otel build and initialization code): I can acquire a meter with var meter = otel.Meter("example.io/package/name")(for example in a package main), build an instrument and call .Add method. But this metric were not been sent to my exporter (stdout)

My goal is to keep build and initialization codes in their own package of the application, so that i cann call this and acquire a meter in my package main. I guess that's a common situation

Is there a way to receive in a package a meter builded in another package or something in this line? Is this a nice practice? The doc brings that usually a MeterProvider is builded once and lives the time the app lives too. this has to be builded in the same package allways?

linked discussion

I have followed this implementation putting this code in a exclusive package of my add. Then my expect was to use a acquired meter in a different package, but i was not able to

Here an example: A main package trying to acquire and use a meter. Otel is initializated in the other package and this func is called in beggining of the execution

package main

import (
    "context"
    "localtest/other"

    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/attribute"
    otm "go.opentelemetry.io/otel/metric"
)

func main() {
    other.Test()

    mainMeter := otel.GetMeterProvider().Meter("localtest/other/myTestMeter")

    mainCounter, _ := mainMeter.Int64Counter(
        "temporary.call",
        otm.WithUnit("{call}"),
        otm.WithDescription("car counter"),
    )
    mainCounter.Add(context.Background(), 1, otm.WithAttributes(
        attribute.String("model", "Camaro"),
        attribute.Bool("IsCar", true),
    ))

}
package other

import (
    "context"

    "log"
    "time"

    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/attribute"
    "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric"
    otm "go.opentelemetry.io/otel/metric"
    "go.opentelemetry.io/otel/sdk/metric"
    "go.opentelemetry.io/otel/sdk/resource"
    semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
)

func Test() {
    res, err := newResource()
    if err != nil {
        panic(err)
    }
    meterProvider, err := newMeterProvider(res)
    if err != nil {
        panic(err)
    }

    defer func() {
        if err := meterProvider.Shutdown(context.Background()); err != nil {
            log.Println(err)
        }
    }()

    otel.SetMeterProvider(meterProvider)

    Meter := otel.Meter("myTestMeter")

    otherCounter, err := Meter.Int64Counter(
        "temporary.call",
        otm.WithUnit("{call}"),
        otm.WithDescription("car counter"),
    )
    otherCounter.Add(context.Background(), 1, otm.WithAttributes(
        attribute.String("model", "Monza"),
        attribute.Bool("IsCar", true),
    ))

}

func newResource() (*resource.Resource, error) {
    return resource.Merge(resource.Default(),
        resource.NewWithAttributes(semconv.SchemaURL,
            semconv.ServiceName("my-service"),
            semconv.ServiceVersion("0.1.0"),
        ))
}

func newMeterProvider(res *resource.Resource) (*metric.MeterProvider, error) {
    metricExporter, err := stdoutmetric.New()
    if err != nil {
        return nil, err
    }

    meterProvider := metric.NewMeterProvider(
        metric.WithResource(res),
        metric.WithReader(metric.NewPeriodicReader(metricExporter,
            // Default is 1m. Set to 3s for demonstrative purposes.
            metric.WithInterval(3*time.Second))),
    )
    return meterProvider, nil
}

Here the output that show only the counter generated in the same package where otel is initializated:

{"Resource":[{"Key":"service.name","Value":{"Type":"STRING","Value":"my-service"}},{"Key":"service.version","Value":{"Type":"STRING","Value":"0.1.0"}},{"Key":"telemetry.sdk.language","Value":{"Type":"STRING","Value":"go"}},{"Key":"telemetry.sdk.name","Value":{"Type":"STRING","Value":"opentelemetry"}},{"Key":"telemetry.sdk.version","Value":{"Type":"STRING","Value":"1.32.0"}}],"ScopeMetrics":[{"Scope":{"Name":"myTestMeter","Version":"","SchemaURL":"","Attributes":null},"Metrics":[{"Name":"temporary.call","Description":"car counter","Unit":"{call}","Data":{"DataPoints":[{"Attributes":[{"Key":"IsCar","Value":{"Type":"BOOL","Value":true}},{"Key":"model","Value":{"Type":"STRING","Value":"Monza"}}],"StartTime":"2024-11-20T07:40:23.831377979-03:00","Time":"2024-11-20T07:40:23.831517987-03:00","Value":1}],"Temporality":"CumulativeTemporality","IsMonotonic":true}}]}]}

According to docs, a meterProvider is essential to build instruments, and that's clear to me. Right after the initializing example of metric initialization, we have the topic aquiring a meter with this object.

Following this implementation in my tests i was note able to properly use meterProvider outside of the package where it's implemented (a package created to hold otel build and initialization code): I can acquire a meter with var meter = otel.Meter("example.io/package/name")(for example in a package main), build an instrument and call .Add method. But this metric were not been sent to my exporter (stdout)

My goal is to keep build and initialization codes in their own package of the application, so that i cann call this and acquire a meter in my package main. I guess that's a common situation

Is there a way to receive in a package a meter builded in another package or something in this line? Is this a nice practice? The doc brings that usually a MeterProvider is builded once and lives the time the app lives too. this has to be builded in the same package allways?

linked discussion

I have followed this implementation putting this code in a exclusive package of my add. Then my expect was to use a acquired meter in a different package, but i was not able to

Here an example: A main package trying to acquire and use a meter. Otel is initializated in the other package and this func is called in beggining of the execution

package main

import (
    "context"
    "localtest/other"

    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/attribute"
    otm "go.opentelemetry.io/otel/metric"
)

func main() {
    other.Test()

    mainMeter := otel.GetMeterProvider().Meter("localtest/other/myTestMeter")

    mainCounter, _ := mainMeter.Int64Counter(
        "temporary.call",
        otm.WithUnit("{call}"),
        otm.WithDescription("car counter"),
    )
    mainCounter.Add(context.Background(), 1, otm.WithAttributes(
        attribute.String("model", "Camaro"),
        attribute.Bool("IsCar", true),
    ))

}
package other

import (
    "context"

    "log"
    "time"

    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/attribute"
    "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric"
    otm "go.opentelemetry.io/otel/metric"
    "go.opentelemetry.io/otel/sdk/metric"
    "go.opentelemetry.io/otel/sdk/resource"
    semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
)

func Test() {
    res, err := newResource()
    if err != nil {
        panic(err)
    }
    meterProvider, err := newMeterProvider(res)
    if err != nil {
        panic(err)
    }

    defer func() {
        if err := meterProvider.Shutdown(context.Background()); err != nil {
            log.Println(err)
        }
    }()

    otel.SetMeterProvider(meterProvider)

    Meter := otel.Meter("myTestMeter")

    otherCounter, err := Meter.Int64Counter(
        "temporary.call",
        otm.WithUnit("{call}"),
        otm.WithDescription("car counter"),
    )
    otherCounter.Add(context.Background(), 1, otm.WithAttributes(
        attribute.String("model", "Monza"),
        attribute.Bool("IsCar", true),
    ))

}

func newResource() (*resource.Resource, error) {
    return resource.Merge(resource.Default(),
        resource.NewWithAttributes(semconv.SchemaURL,
            semconv.ServiceName("my-service"),
            semconv.ServiceVersion("0.1.0"),
        ))
}

func newMeterProvider(res *resource.Resource) (*metric.MeterProvider, error) {
    metricExporter, err := stdoutmetric.New()
    if err != nil {
        return nil, err
    }

    meterProvider := metric.NewMeterProvider(
        metric.WithResource(res),
        metric.WithReader(metric.NewPeriodicReader(metricExporter,
            // Default is 1m. Set to 3s for demonstrative purposes.
            metric.WithInterval(3*time.Second))),
    )
    return meterProvider, nil
}

Here the output that show only the counter generated in the same package where otel is initializated:

{"Resource":[{"Key":"service.name","Value":{"Type":"STRING","Value":"my-service"}},{"Key":"service.version","Value":{"Type":"STRING","Value":"0.1.0"}},{"Key":"telemetry.sdk.language","Value":{"Type":"STRING","Value":"go"}},{"Key":"telemetry.sdk.name","Value":{"Type":"STRING","Value":"opentelemetry"}},{"Key":"telemetry.sdk.version","Value":{"Type":"STRING","Value":"1.32.0"}}],"ScopeMetrics":[{"Scope":{"Name":"myTestMeter","Version":"","SchemaURL":"","Attributes":null},"Metrics":[{"Name":"temporary.call","Description":"car counter","Unit":"{call}","Data":{"DataPoints":[{"Attributes":[{"Key":"IsCar","Value":{"Type":"BOOL","Value":true}},{"Key":"model","Value":{"Type":"STRING","Value":"Monza"}}],"StartTime":"2024-11-20T07:40:23.831377979-03:00","Time":"2024-11-20T07:40:23.831517987-03:00","Value":1}],"Temporality":"CumulativeTemporality","IsMonotonic":true}}]}]}
Share Improve this question asked Nov 21, 2024 at 18:00 ramon perezramon perez 211 silver badge4 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You are shutting down the generated metric.MeterProvider at the end of your other.Test function (when the defer is executed), so when the rest of main is running the meter provider is already shut down and:

Measurements made by instruments from meters this MeterProvider created will not be exported after Shutdown is called.

You'll have to shut down the generated metric.MeterProvider and the end of the program run, for example be returning a structure from other.Test on which you can ShutDown or storing the metric.MeterProvider in a global variable and creating a function other.TestShutdown, like:

package other

// ...

var meterProvider *metric.MeterProvider

func Test() {
    // ...
    meterProvider, err = newMeterProvider(res)
    // remove meterProvider.Shutdown from this function
    // ...
}

func TestShutdown() {
    if err := meterProvider.Shutdown(context.Background()); err != nil {
        log.Println(err)
    }
}

and call it like:

package main

// ...

func main() {
    other.Test()
    defer other.TestShutdown()
// ...
}

本文标签: metricsOpen TelemetrygoHow global a MeterProvider really isStack Overflow