github.com/nikandfor/tlog@v0.21.5-0.20231108111739-3ef89426a96d/ext/tlslog/slog_test.go (about)

     1  package tlslog
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  	"io"
     7  	"os"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  	"golang.org/x/exp/slog"
    13  
    14  	"github.com/nikandfor/tlog"
    15  	"github.com/nikandfor/tlog/convert"
    16  	"github.com/nikandfor/tlog/tlwire"
    17  )
    18  
    19  func TestSlog(t *testing.T) {
    20  	var b bytes.Buffer
    21  	d := tlwire.NewDumper(os.Stderr)
    22  	w := io.MultiWriter(d, &b)
    23  	l := tlog.New(w)
    24  	h := Wrap(l)
    25  	s := slog.New(h)
    26  
    27  	s.Info("message", "a", "b", "c", 4)
    28  
    29  	ss := s.With("a", "b", "c", 5)
    30  	ss.Warn("warning", "d", errors.New("holy error"))
    31  
    32  	ss = s.With("a", "b").WithGroup("group").With("c", 6).WithGroup("group2").With("d", "e")
    33  
    34  	ss.Info("go deeper", slog.Group("gr", slog.Duration("d", time.Second)))
    35  
    36  	s.Info("corner cases", "", "b", slog.Group("", slog.String("embedded", "value"), slog.Group("omitted")))
    37  
    38  	//
    39  
    40  	var bb bytes.Buffer
    41  
    42  	lfw := convert.NewLogfmt(&bb)
    43  	rew := convert.NewRewriter(lfw)
    44  	rew.Rule = convert.NewKeyRenamer(nil, convert.RenameRule{
    45  		Path: []tlog.RawMessage{
    46  			rew.AppendString(nil, tlog.KeyTimestamp),
    47  			tlog.RawTag(tlwire.Semantic, tlwire.Time),
    48  		},
    49  		Remove: true,
    50  	}, convert.RenameRule{
    51  		Path: []tlog.RawMessage{
    52  			rew.AppendString(nil, tlog.KeyCaller),
    53  			tlog.RawTag(tlwire.Semantic, tlwire.Caller),
    54  		},
    55  		Remove: true,
    56  	}, convert.RenameRule{
    57  		Path: []tlog.RawMessage{
    58  			rew.AppendString(nil, tlog.KeyLogLevel),
    59  			tlog.RawTag(tlwire.Semantic, tlog.WireLogLevel),
    60  		},
    61  		Rename: []byte("level"),
    62  	})
    63  
    64  	_, err := convert.Copy(rew, &b)
    65  	assert.NoError(t, err)
    66  	assert.Equal(t, `
    67  _m=message  a=b  c=4
    68  _m=warning  level=1  a=b  c=5  d="holy error"
    69  _m="go deeper"  a=b  group.c=6  group.group2.d=e  group.group2.gr.d=1000000000
    70  _m="corner cases"  embedded=value
    71  `, "\n"+bb.String())
    72  }