2018-11-30 23:50:23 +00:00
|
|
|
package mlog
|
|
|
|
|
|
|
|
import (
|
2019-02-05 20:18:17 +00:00
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
"strings"
|
2018-11-30 23:50:23 +00:00
|
|
|
. "testing"
|
|
|
|
|
|
|
|
"github.com/mediocregopher/mediocre-go-lib/mctx"
|
|
|
|
"github.com/mediocregopher/mediocre-go-lib/mtest/massert"
|
|
|
|
)
|
|
|
|
|
2019-02-05 20:18:17 +00:00
|
|
|
func TestContextLogging(t *T) {
|
2018-11-30 23:50:23 +00:00
|
|
|
|
2019-02-05 20:18:17 +00:00
|
|
|
var lines []string
|
2019-01-30 21:06:24 +00:00
|
|
|
l := NewLogger()
|
|
|
|
l.SetHandler(func(msg Message) error {
|
2019-02-05 20:18:17 +00:00
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
if err := DefaultFormat(buf, msg); err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
lines = append(lines, strings.TrimSuffix(buf.String(), "\n"))
|
2018-11-30 23:50:23 +00:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
2019-02-05 20:18:17 +00:00
|
|
|
ctx := Set(context.Background(), l)
|
|
|
|
ctx1 := mctx.NewChild(ctx, "1")
|
|
|
|
ctx1a := mctx.NewChild(ctx1, "a")
|
|
|
|
ctx1b := mctx.NewChild(ctx1, "b")
|
|
|
|
ctx1 = mctx.WithChild(ctx1, ctx1a)
|
|
|
|
ctx1 = mctx.WithChild(ctx1, ctx1b)
|
|
|
|
ctx = mctx.WithChild(ctx, ctx1)
|
2018-11-30 23:50:23 +00:00
|
|
|
|
2019-02-05 20:18:17 +00:00
|
|
|
From(ctx).Info(ctx1a, "ctx1a")
|
|
|
|
From(ctx).Info(ctx1, "ctx1")
|
|
|
|
From(ctx).Info(ctx, "ctx")
|
|
|
|
From(ctx).Debug(ctx1b, "ctx1b (shouldn't show up)")
|
|
|
|
From(ctx).Info(ctx1b, "ctx1b")
|
|
|
|
|
|
|
|
ctx2 := mctx.NewChild(ctx, "2")
|
|
|
|
ctx = mctx.WithChild(ctx, ctx2)
|
|
|
|
From(ctx2).Info(ctx2, "ctx2")
|
2018-11-30 23:50:23 +00:00
|
|
|
|
|
|
|
massert.Fatal(t, massert.All(
|
2019-02-05 20:18:17 +00:00
|
|
|
massert.Len(lines, 5),
|
|
|
|
massert.Equal(lines[0], "~ INFO -- (/1/a) ctx1a"),
|
|
|
|
massert.Equal(lines[1], "~ INFO -- (/1) ctx1"),
|
|
|
|
massert.Equal(lines[2], "~ INFO -- ctx"),
|
|
|
|
massert.Equal(lines[3], "~ INFO -- (/1/b) ctx1b"),
|
|
|
|
massert.Equal(lines[4], "~ INFO -- (/2) ctx2"),
|
2018-11-30 23:50:23 +00:00
|
|
|
))
|
2019-01-30 21:06:24 +00:00
|
|
|
|
2019-02-05 20:18:17 +00:00
|
|
|
// changing MaxLevel on ctx's Logger should change it for all
|
|
|
|
From(ctx).SetMaxLevel(DebugLevel)
|
2019-01-30 21:06:24 +00:00
|
|
|
|
2019-02-05 20:18:17 +00:00
|
|
|
lines = lines[:0]
|
|
|
|
From(ctx).Info(ctx, "ctx")
|
|
|
|
From(ctx).Debug(ctx, "ctx debug")
|
|
|
|
From(ctx2).Debug(ctx2, "ctx2 debug")
|
2019-01-30 21:06:24 +00:00
|
|
|
|
|
|
|
massert.Fatal(t, massert.All(
|
2019-02-05 20:18:17 +00:00
|
|
|
massert.Len(lines, 3),
|
|
|
|
massert.Equal(lines[0], "~ INFO -- ctx"),
|
|
|
|
massert.Equal(lines[1], "~ DEBUG -- ctx debug"),
|
|
|
|
massert.Equal(lines[2], "~ DEBUG -- (/2) ctx2 debug"),
|
2019-01-30 21:06:24 +00:00
|
|
|
))
|
2018-11-30 23:50:23 +00:00
|
|
|
}
|