github.com/castai/kvisor@v1.7.1-0.20240516114728-b3572a2607b5/pkg/logging/logging_test.go (about)

     1  package logging_test
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"errors"
     7  	"log/slog"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/castai/kvisor/pkg/logging"
    12  	"github.com/stretchr/testify/require"
    13  	"golang.org/x/time/rate"
    14  )
    15  
    16  func TestLogger(t *testing.T) {
    17  	t.Run("print long", func(t *testing.T) {
    18  		log := logging.New(&logging.Config{
    19  			Level:     logging.MustParseLevel("DEBUG"),
    20  			AddSource: true,
    21  		})
    22  
    23  		log.Errorf("something wrong: %v", errors.New("ups"))
    24  		serverLog := log.WithField("component", "server")
    25  		serverLog.Info("with component")
    26  		serverLog.Info("more server logs")
    27  	})
    28  
    29  	t.Run("rate limit", func(t *testing.T) {
    30  		var out bytes.Buffer
    31  		log := logging.New(&logging.Config{
    32  			Output: &out,
    33  			Level:  logging.MustParseLevel("DEBUG"),
    34  			RateLimiter: logging.RateLimiterConfig{
    35  				Limit: rate.Every(10 * time.Millisecond),
    36  				Burst: 1,
    37  			},
    38  		})
    39  
    40  		for i := 0; i < 10; i++ {
    41  			log.WithField("component", "test").Info("test")
    42  			time.Sleep(6 * time.Millisecond)
    43  		}
    44  
    45  		require.GreaterOrEqual(t, 5, countLogLines(&out))
    46  	})
    47  
    48  	t.Run("export logs", func(t *testing.T) {
    49  		exportedLogs := make(chan slog.Record, 1)
    50  		log := logging.New(&logging.Config{
    51  			Level: logging.MustParseLevel("DEBUG"),
    52  			Export: logging.ExportConfig{
    53  				ExportFunc: func(ctx context.Context, record slog.Record) {
    54  					exportedLogs <- record
    55  				},
    56  				MinLevel: slog.LevelInfo,
    57  			},
    58  		})
    59  
    60  		//log.Debug("should not export debug")
    61  		log.WithField("component", "test").Error("should export error")
    62  
    63  		select {
    64  		case logRecord := <-exportedLogs:
    65  			require.Equal(t, logRecord.Message, "should export error")
    66  		case <-time.After(time.Second):
    67  			t.Fatal("timeout")
    68  		}
    69  	})
    70  }
    71  
    72  func countLogLines(buf *bytes.Buffer) int {
    73  	var n int
    74  	for _, b := range buf.Bytes() {
    75  		if b == '\n' {
    76  			n++
    77  		}
    78  	}
    79  	return n
    80  }