github.com/anycable/anycable-go@v1.5.1/metrics/printer.go (about)

     1  package metrics
     2  
     3  import (
     4  	"log/slog"
     5  	"strings"
     6  
     7  	"github.com/anycable/anycable-go/utils"
     8  )
     9  
    10  // Printer describes metrics logging interface
    11  type Printer interface {
    12  	Print(snapshot map[string]int64)
    13  }
    14  
    15  // BasePrinter simply logs stats as structured log
    16  type BasePrinter struct {
    17  	filter map[string]struct{}
    18  
    19  	log *slog.Logger
    20  }
    21  
    22  // NewBasePrinter returns new base printer struct
    23  func NewBasePrinter(filterList []string, l *slog.Logger) *BasePrinter {
    24  	var filter map[string]struct{}
    25  
    26  	if filterList != nil {
    27  		filter = make(map[string]struct{}, len(filterList))
    28  		for _, k := range filterList {
    29  			filter[k] = struct{}{}
    30  		}
    31  	}
    32  
    33  	return &BasePrinter{filter: filter, log: l}
    34  }
    35  
    36  // Run prints a message to the log with metrics logging details
    37  func (p *BasePrinter) Run(interval int) error {
    38  	if p.filter != nil {
    39  		p.log.Info("log metrics", "interval", interval, "fields", strings.Join(utils.Keys(p.filter), ","))
    40  	} else {
    41  		p.log.Info("log metrics", "interval", interval)
    42  	}
    43  	return nil
    44  }
    45  
    46  func (p *BasePrinter) Stop() {
    47  }
    48  
    49  // Write prints formatted snapshot to the log
    50  func (p *BasePrinter) Write(m *Metrics) error {
    51  	snapshot := m.IntervalSnapshot()
    52  	p.Print(snapshot)
    53  	return nil
    54  }
    55  
    56  // Print logs stats data using global logger with info level
    57  func (p *BasePrinter) Print(snapshot map[string]uint64) {
    58  	fields := make([]interface{}, 0)
    59  
    60  	for k, v := range snapshot {
    61  		if p.filter == nil {
    62  			fields = append(fields, k, v)
    63  		} else if _, ok := p.filter[k]; ok {
    64  			fields = append(fields, k, v)
    65  		}
    66  	}
    67  
    68  	p.log.Info("", fields...)
    69  }