github.com/anycable/anycable-go@v1.5.1/logger/values.go (about)

     1  package logger
     2  
     3  import (
     4  	"fmt"
     5  	"log/slog"
     6  )
     7  
     8  const (
     9  	maxValueLength = 100
    10  )
    11  
    12  type compactValue[T string | []byte] struct {
    13  	val T
    14  }
    15  
    16  func (c *compactValue[T]) LogValue() slog.Value {
    17  	return slog.StringValue(c.String())
    18  }
    19  
    20  func (c *compactValue[T]) String() string {
    21  	val := string(c.val)
    22  
    23  	if len(val) > maxValueLength {
    24  		return fmt.Sprintf("%s...(%d)", val[:maxValueLength], len(val)-maxValueLength)
    25  	}
    26  
    27  	return val
    28  }
    29  
    30  // CompactValue wraps any scalar value to show it in log truncated
    31  func CompactValue[T string | []byte](v T) *compactValue[T] {
    32  	return &compactValue[T]{val: v}
    33  }
    34  
    35  func CompactValues[T string | []byte, S []T](v S) []*compactValue[T] {
    36  	res := make([]*compactValue[T], len(v))
    37  	for i, val := range v {
    38  		res[i] = CompactValue(val)
    39  	}
    40  
    41  	return res
    42  }
    43  
    44  type compactAny struct {
    45  	val interface{}
    46  }
    47  
    48  func (c *compactAny) String() string {
    49  	val := fmt.Sprintf("%+v", c.val)
    50  
    51  	if len(val) > maxValueLength {
    52  		return fmt.Sprintf("%s...(%d)", val[:maxValueLength], len(val)-maxValueLength)
    53  	}
    54  
    55  	return val
    56  }
    57  
    58  func (c *compactAny) LogValue() slog.Value {
    59  	return slog.StringValue(c.String())
    60  }
    61  
    62  // CompactAny wraps any value to show it in log truncated
    63  func CompactAny(val interface{}) *compactAny {
    64  	return &compactAny{val}
    65  }