github.com/phuslu/log@v1.0.100/slog_test.go (about)

     1  //go:build go1.21
     2  // +build go1.21
     3  
     4  package log
     5  
     6  import (
     7  	"log/slog"
     8  	"os"
     9  	"testing"
    10  )
    11  
    12  func TestSlogJsonHandler(t *testing.T) {
    13  	logger := slog.New(SlogNewJSONHandler(os.Stderr, &slog.HandlerOptions{AddSource: false}))
    14  
    15  	logger1 := logger.WithGroup("g").With("1", "2").With("3", "4")
    16  	logger1.Info("hello from group slog 1", "number", 42)
    17  	logger1.Info("hello from group slog 2")
    18  
    19  	logger2 := logger1.WithGroup("g1").With("a", "b").With("c", "d").
    20  		WithGroup("g2").With("foo", "bar").With("bar", "foo").
    21  		WithGroup("g3").With("x", 1).With("y", 2).With("z", 3)
    22  	logger2.Info("hello from group slog 3", "number", 42)
    23  	logger2.Info("hello from group slog 4")
    24  
    25  	logger1.Info("hello from group slog 1", "number", 42)
    26  	logger1.WithGroup("group").Info("hello from group slog 2", "number", 42)
    27  }
    28  
    29  func TestSlogJsonHandlerClosed(t *testing.T) {
    30  	logger := slog.New(SlogNewJSONHandler(os.Stderr, &slog.HandlerOptions{AddSource: false}))
    31  
    32  	logger1 := logger.WithGroup("g").With("number", 42).WithGroup("g1")
    33  	logger1.Info("hello from group slog 1", "a", 1, "b", 2)
    34  	logger1.With("x", "1", "y", "2").Info("hello from group slog 2", "a", 1, "b", 2)
    35  	logger1.Info("hello from group slog 3")
    36  }
    37  
    38  func TestSlogJsonHandlerGroups(t *testing.T) {
    39  	logger := slog.New(SlogNewJSONHandler(os.Stderr, &slog.HandlerOptions{AddSource: true}))
    40  
    41  	logger.WithGroup("group1").WithGroup("group2").Info("hello from slog groups", slog.Group("subGroup", "a", 1, "b", 2))
    42  	logger.WithGroup("group1").WithGroup("group2").Info("hello from slog groups", slog.Group("subGroup"))
    43  	logger.WithGroup("group1").WithGroup("group2").Info("hello from slog groups")
    44  }
    45  
    46  func TestSlogJsonHandlerAny(t *testing.T) {
    47  	logger := slog.New(SlogNewJSONHandler(os.Stderr, &slog.HandlerOptions{AddSource: true}))
    48  
    49  	var obj = struct {
    50  		Rate string
    51  		Low  int
    52  		High float32
    53  	}{"15", 16, 123.2}
    54  
    55  	logger.Info("hello from slog any", "good object", obj)
    56  
    57  	logger.Info("hello from slog any", "bad object", logger.Info)
    58  }