github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/countlog/output/compact/compact_test.go (about)

     1  package compact
     2  
     3  import (
     4  	"testing"
     5  	"github.com/stretchr/testify/require"
     6  	"time"
     7  	"github.com/v2pro/plz/countlog/spi"
     8  )
     9  
    10  func Test_compact_string(t *testing.T) {
    11  	should := require.New(t)
    12  	now := time.Now()
    13  	formatted := format(0, "event!abc", "file", 17, &spi.Event{
    14  		Timestamp: now,
    15  		Properties: []interface{}{
    16  			"k1", "hello",
    17  			"k2", []byte("abc"),
    18  		},
    19  	})
    20  	should.Equal(`abc||timestamp=`+
    21  		now.Format(time.RFC3339)+
    22  		`||k1=hello||k2=abc`+ "\n", string(formatted))
    23  }
    24  
    25  func Test_callee(t *testing.T) {
    26  	should := require.New(t)
    27  	now := time.Now()
    28  	formatted := format(0, "callee!abc", "file", 17, &spi.Event{
    29  		Timestamp: now,
    30  		Properties: []interface{}{
    31  		},
    32  	})
    33  	should.Equal(`call abc||timestamp=`+now.Format(time.RFC3339)+"\n",
    34  		string(formatted))
    35  }
    36  
    37  func Test_format_msg(t *testing.T) {
    38  	should := require.New(t)
    39  	now := time.Now()
    40  	formatted := format(0, "{k1}~{k2}", "file", 17, &spi.Event{
    41  		Timestamp: now,
    42  		Properties: []interface{}{
    43  			"k1", "hello",
    44  			"k2", []byte("abc"),
    45  		},
    46  	})
    47  	should.Equal(`hello~abc||timestamp=`+
    48  		now.Format(time.RFC3339)+
    49  		`||k1=hello||k2=abc`+ "\n", string(formatted))
    50  }
    51  
    52  func format(level int, eventName string,
    53  	callerFile string, callerLine int, event *spi.Event) []byte {
    54  	format := &Format{}
    55  	formatter := format.FormatterOf(&spi.LogSite{
    56  		File:   callerFile,
    57  		Line:   callerLine,
    58  		Event:  eventName,
    59  		Sample: event.Properties,
    60  	})
    61  	return formatter.Format(nil, event)
    62  }
    63  
    64  func Benchmark_compact_string(b *testing.B) {
    65  	format := &Format{}
    66  	formatter := format.FormatterOf(&spi.LogSite{
    67  		File:  "file",
    68  		Line:  17,
    69  		Event: "event!abc",
    70  		Sample: []interface{}{
    71  			"k1", "v1",
    72  			"k2", []byte(nil),
    73  		},
    74  	})
    75  	event := &spi.Event{
    76  		Properties: []interface{}{
    77  			"k1", "hello",
    78  			"k2", []byte("中文"),
    79  		},
    80  	}
    81  	var space []byte
    82  	b.ReportAllocs()
    83  	for i := 0; i < b.N; i++ {
    84  		space = space[:0]
    85  		space = formatter.Format(space, event)
    86  	}
    87  }