github.com/adevinta/lava@v0.7.2/internal/metrics/metrics.go (about)

     1  // Copyright 2023 Adevinta
     2  
     3  // Package metrics collects Lava execution metrics.
     4  package metrics
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"io"
    10  	"os"
    11  	"sync"
    12  )
    13  
    14  // DefaultCollector is the default [Collector].
    15  var DefaultCollector = NewCollector()
    16  
    17  // Collector represents a metrics collector.
    18  type Collector struct {
    19  	mutex   sync.Mutex
    20  	metrics map[string]any
    21  }
    22  
    23  // NewCollector returns a new metrics collector.
    24  func NewCollector() *Collector {
    25  	return &Collector{
    26  		metrics: make(map[string]any),
    27  	}
    28  }
    29  
    30  // Collect records a metric with the provided name and value.
    31  func (c *Collector) Collect(name string, value any) {
    32  	c.mutex.Lock()
    33  	defer c.mutex.Unlock()
    34  
    35  	c.metrics[name] = value
    36  }
    37  
    38  // Write writes the metrics to the specified [io.Writer].
    39  func (c *Collector) Write(w io.Writer) error {
    40  	enc := json.NewEncoder(w)
    41  	enc.SetIndent("", "  ")
    42  	if err := enc.Encode(c.metrics); err != nil {
    43  		return fmt.Errorf("encode JSON: %w", err)
    44  	}
    45  	return nil
    46  }
    47  
    48  // Collect records a metric with the provided name and value using
    49  // [DefaultCollector].
    50  func Collect(name string, value any) {
    51  	DefaultCollector.Collect(name, value)
    52  }
    53  
    54  // Write writes the collected metrics to the specified [io.Writer]
    55  // using [DefaultCollector].
    56  func Write(w io.Writer) error {
    57  	return DefaultCollector.Write(w)
    58  }
    59  
    60  // WriteFile writes the collected metrics into the specified file
    61  // using [DefaultCollector].
    62  func WriteFile(file string) error {
    63  	f, err := os.Create(file)
    64  	if err != nil {
    65  		return fmt.Errorf("create file: %w", err)
    66  	}
    67  	defer f.Close()
    68  
    69  	return Write(f)
    70  }