github.com/siglens/siglens@v0.0.0-20240328180423-f7ce9ae441ed/pkg/instrumentation/metrics.go (about)

     1  /*
     2  Copyright 2023.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package instrumentation
    18  
    19  import (
    20  	"context"
    21  	"net/http"
    22  
    23  	log "github.com/sirupsen/logrus"
    24  
    25  	"github.com/prometheus/client_golang/prometheus/promhttp"
    26  	conf "github.com/siglens/siglens/pkg/config"
    27  	"go.opentelemetry.io/otel"
    28  	"go.opentelemetry.io/otel/attribute"
    29  	"go.opentelemetry.io/otel/exporters/prometheus"
    30  	api "go.opentelemetry.io/otel/metric"
    31  	"go.opentelemetry.io/otel/sdk/metric"
    32  )
    33  
    34  var meter = otel.GetMeterProvider().Meter("siglens")
    35  var ctx = context.Background()
    36  var commonAttributes []attribute.KeyValue
    37  
    38  var metricsPkgInitialized bool
    39  
    40  func InitMetrics() {
    41  	if metricsPkgInitialized {
    42  		return
    43  	}
    44  	exporter, err := prometheus.New()
    45  	if err != nil {
    46  		log.Errorf("Failed to initialize prometheus exporter: %v", err)
    47  	}
    48  	provider := metric.NewMeterProvider(metric.WithReader(exporter))
    49  	otel.SetMeterProvider(provider)
    50  
    51  	commonAttributes = append(commonAttributes, attribute.String("hostname", conf.GetHostID()))
    52  	registerGaugeCallbacks()
    53  
    54  	http.Handle("/metrics", promhttp.Handler())
    55  	go func() {
    56  		_ = http.ListenAndServe(":2222", nil)
    57  	}()
    58  
    59  	log.Infof("OpenTelemetry Prometheus exporter running on :2222")
    60  	metricsPkgInitialized = true
    61  }
    62  
    63  func IncrementInt64Counter(metricName api.Int64Counter, value int64) {
    64  	metricName.Add(ctx, value)
    65  }
    66  
    67  func IncrementInt64UpDownCounter(metricName api.Int64UpDownCounter, value int64) {
    68  	metricName.Add(
    69  		ctx,
    70  		value,
    71  	)
    72  }
    73  
    74  func IncrementInt64CounterWithLabel(metricName api.Int64Counter, value int64,
    75  	labelKey string, labelVal string) {
    76  	attrs := []attribute.KeyValue{
    77  		attribute.String(labelKey, labelVal),
    78  	}
    79  
    80  	metricName.Add(
    81  		ctx,
    82  		value,
    83  		api.WithAttributes(attrs...),
    84  	)
    85  }