69 lines
1.8 KiB
Go
69 lines
1.8 KiB
Go
|
|
package starlog
|
||
|
|
|
||
|
|
import (
|
||
|
|
"bytes"
|
||
|
|
"context"
|
||
|
|
"strings"
|
||
|
|
"testing"
|
||
|
|
)
|
||
|
|
|
||
|
|
func TestInfoContextShortcut(t *testing.T) {
|
||
|
|
var buf bytes.Buffer
|
||
|
|
logger := newStructuredTestLogger(&buf)
|
||
|
|
logger.SetContextFieldExtractor(func(ctx context.Context) Fields {
|
||
|
|
traceID, _ := ctx.Value("trace_id").(string)
|
||
|
|
if traceID == "" {
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
return Fields{"trace_id": traceID}
|
||
|
|
})
|
||
|
|
|
||
|
|
ctx := context.WithValue(context.Background(), "trace_id", "t-1")
|
||
|
|
logger.InfoContext(ctx, "hello")
|
||
|
|
|
||
|
|
got := buf.String()
|
||
|
|
if !strings.Contains(got, "hello") || !strings.Contains(got, "trace_id=t-1") {
|
||
|
|
t.Fatalf("InfoContext should carry context fields, got %q", got)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestErrorContextShortcut(t *testing.T) {
|
||
|
|
var buf bytes.Buffer
|
||
|
|
logger := newStructuredTestLogger(&buf)
|
||
|
|
logger.SetContextFieldExtractor(func(ctx context.Context) Fields {
|
||
|
|
rid, _ := ctx.Value("rid").(string)
|
||
|
|
if rid == "" {
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
return Fields{"rid": rid}
|
||
|
|
})
|
||
|
|
|
||
|
|
ctx := context.WithValue(context.Background(), "rid", "req-9")
|
||
|
|
logger.ErrorContext(ctx, "fail")
|
||
|
|
|
||
|
|
got := buf.String()
|
||
|
|
if !strings.Contains(got, "fail") || !strings.Contains(got, "rid=req-9") {
|
||
|
|
t.Fatalf("ErrorContext should carry context fields, got %q", got)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestLogContextShortcut(t *testing.T) {
|
||
|
|
var buf bytes.Buffer
|
||
|
|
logger := newStructuredTestLogger(&buf)
|
||
|
|
logger.SetContextFieldExtractor(func(ctx context.Context) Fields {
|
||
|
|
module, _ := ctx.Value("module").(string)
|
||
|
|
if module == "" {
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
return Fields{"module": module}
|
||
|
|
})
|
||
|
|
|
||
|
|
ctx := context.WithValue(context.Background(), "module", "billing")
|
||
|
|
logger.LogContext(ctx, false, LvNotice, "ctx-log")
|
||
|
|
|
||
|
|
got := buf.String()
|
||
|
|
if !strings.Contains(got, "ctx-log") || !strings.Contains(got, "module=billing") {
|
||
|
|
t.Fatalf("LogContext should carry context fields, got %q", got)
|
||
|
|
}
|
||
|
|
}
|