github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/logger/util.go (about)

     1  package logger
     2  
     3  import (
     4  	"fmt"
     5  	"log/slog"
     6  
     7  	"go.opentelemetry.io/otel/attribute"
     8  
     9  	"github.com/machinefi/w3bstream/pkg/depends/x/textx"
    10  )
    11  
    12  func KVsToAttr(kvs ...any) (atts []attribute.KeyValue) {
    13  	n := len(kvs)
    14  	if n > 0 && n%2 == 0 {
    15  		atts = make([]attribute.KeyValue, n/2)
    16  		for i := range atts {
    17  			k, v := kvs[2*i], kvs[2*i+1]
    18  
    19  			if key, ok := k.(string); ok {
    20  				val, err := textx.MarshalText(v)
    21  				if err != nil {
    22  					continue
    23  				}
    24  				atts[i].Key = attribute.Key(key)
    25  				atts[i].Value = attribute.StringValue(string(val))
    26  			}
    27  		}
    28  		return atts
    29  	}
    30  	return nil
    31  }
    32  
    33  func KVsToSlogAttr(kvs ...interface{}) (attr []slog.Attr) {
    34  	if len(kvs)%2 != 0 {
    35  		return nil
    36  	}
    37  
    38  	for i := 0; i < len(kvs); i += 2 {
    39  		attr = append(attr, slog.Any(fmt.Sprintf("%v", kvs[i]), kvs[i+1]))
    40  	}
    41  
    42  	return
    43  }