diff --git a/global.go b/global.go index 5d00254..c50bd67 100644 --- a/global.go +++ b/global.go @@ -59,6 +59,12 @@ func Fatal(msg string, fields ...zap.Field) { L().WithOptions(zap.AddCallerSkip(1)).Fatal(msg, fields...) } +// With creates a child logger and adds structured context to it. +// Fields added to the child don't affect the parent, and vice versa. +func With(fields ...zap.Field) *zap.Logger { + return L().WithOptions(zap.AddCallerSkip(1)).With(fields...) +} + // SetLevel alters the logging level. func SetLevel(l zapcore.Level) { _globalP.Level.SetLevel(l) diff --git a/log_test.go b/log_test.go index f2ec42c..02d9bda 100644 --- a/log_test.go +++ b/log_test.go @@ -15,6 +15,7 @@ package log import ( . "github.com/pingcap/check" + "go.uber.org/zap" ) var _ = Suite(&testLogSuite{}) @@ -30,4 +31,12 @@ func (t *testLogSuite) TestExport(c *C) { Warn("Testing") Error("Testing") lg.AssertContains("log_test.go:") + + lg = newZapTestLogger(conf, c) + ReplaceGlobals(lg.Logger, nil) + logger := With(zap.String("name", "tester"), zap.Int64("age", 42)) + logger.Info("hello") + logger.Debug("world") + lg.AssertContains(`name=tester`) + lg.AssertContains(`age=42`) }