Skip to content

Commit

Permalink
log: Unexport Context and change With and WithPrefix to top level fun…
Browse files Browse the repository at this point in the history
…ctions.
  • Loading branch information
ChrisHines committed Mar 5, 2017
1 parent 43a8a37 commit d4d0b60
Show file tree
Hide file tree
Showing 14 changed files with 67 additions and 84 deletions.
4 changes: 2 additions & 2 deletions benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
)

func benchmarkRunner(b *testing.B, logger log.Logger, f func(log.Logger)) {
lc := log.NewContext(logger).With("common_key", "common_value")
lc := log.With(logger, "common_key", "common_value")
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
Expand All @@ -17,5 +17,5 @@ func benchmarkRunner(b *testing.B, logger log.Logger, f func(log.Logger)) {

var (
baseMessage = func(logger log.Logger) { logger.Log("foo_key", "foo_value") }
withMessage = func(logger log.Logger) { log.NewContext(logger).With("a", "b").Log("c", "d") }
withMessage = func(logger log.Logger) { log.With(logger, "a", "b").Log("c", "d") }
)
16 changes: 8 additions & 8 deletions deprecated_levels/levels.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import "github.com/go-kit/kit/log"
// want a different set of levels, you can create your own levels type very
// easily, and you can elide the configuration.
type Levels struct {
ctx *log.Context
logger log.Logger
levelKey string

// We have a choice between storing level values in string fields or
Expand All @@ -34,7 +34,7 @@ type Levels struct {
// New creates a new leveled logger, wrapping the passed logger.
func New(logger log.Logger, options ...Option) Levels {
l := Levels{
ctx: log.NewContext(logger),
logger: logger,
levelKey: "level",

debugValue: "debug",
Expand All @@ -52,7 +52,7 @@ func New(logger log.Logger, options ...Option) Levels {
// With returns a new leveled logger that includes keyvals in all log events.
func (l Levels) With(keyvals ...interface{}) Levels {
return Levels{
ctx: l.ctx.With(keyvals...),
logger: log.With(l.logger, keyvals...),
levelKey: l.levelKey,
debugValue: l.debugValue,
infoValue: l.infoValue,
Expand All @@ -64,27 +64,27 @@ func (l Levels) With(keyvals ...interface{}) Levels {

// Debug returns a debug level logger.
func (l Levels) Debug() log.Logger {
return l.ctx.WithPrefix(l.levelKey, l.debugValue)
return log.WithPrefix(l.logger, l.levelKey, l.debugValue)
}

// Info returns an info level logger.
func (l Levels) Info() log.Logger {
return l.ctx.WithPrefix(l.levelKey, l.infoValue)
return log.WithPrefix(l.logger, l.levelKey, l.infoValue)
}

// Warn returns a warning level logger.
func (l Levels) Warn() log.Logger {
return l.ctx.WithPrefix(l.levelKey, l.warnValue)
return log.WithPrefix(l.logger, l.levelKey, l.warnValue)
}

// Error returns an error level logger.
func (l Levels) Error() log.Logger {
return l.ctx.WithPrefix(l.levelKey, l.errorValue)
return log.WithPrefix(l.logger, l.levelKey, l.errorValue)
}

// Crit returns a critical level logger.
func (l Levels) Crit() log.Logger {
return l.ctx.WithPrefix(l.levelKey, l.critValue)
return log.WithPrefix(l.logger, l.levelKey, l.critValue)
}

// Option sets a parameter for leveled loggers.
Expand Down
4 changes: 2 additions & 2 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
// resulting log output. We can use a context to improve the RunTask example.
//
// func RunTask(task Task, logger log.Logger) string {
// logger = log.NewContext(logger).With("taskID", task.ID)
// logger = log.With(logger, "taskID", task.ID)
// logger.Log("event", "starting task")
// ...
// taskHelper(task.Cmd, logger)
Expand Down Expand Up @@ -72,7 +72,7 @@
// entries contain a timestamp and source location looks like this:
//
// logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout))
// logger = log.NewContext(logger).With("ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller)
// logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller)
//
// Concurrent Safety
//
Expand Down
6 changes: 3 additions & 3 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func Example_context() {
}

RunTask := func(task Task, logger log.Logger) {
logger = log.NewContext(logger).With("taskID", task.ID)
logger = log.With(logger, "taskID", task.ID)
logger.Log("event", "starting task")

taskHelper(task.Cmd, logger)
Expand All @@ -68,7 +68,7 @@ func Example_valuer() {
return count
}

logger = log.NewContext(logger).With("count", log.Valuer(counter))
logger = log.With(logger, "count", log.Valuer(counter))

logger.Log("call", "first")
logger.Log("call", "second")
Expand All @@ -88,7 +88,7 @@ func Example_debugInfo() {
return baseTime
}

logger = log.NewContext(logger).With("time", log.Timestamp(mockTime), "caller", log.DefaultCaller)
logger = log.With(logger, "time", log.Timestamp(mockTime), "caller", log.DefaultCaller)

logger.Log("call", "first")
logger.Log("call", "second")
Expand Down
2 changes: 1 addition & 1 deletion json_logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func TestJSONLoggerCaller(t *testing.T) {
t.Parallel()
buf := &bytes.Buffer{}
logger := log.NewJSONLogger(buf)
logger = log.NewContext(logger).With("caller", log.DefaultCaller)
logger = log.With(logger, "caller", log.DefaultCaller)

if err := logger.Log(); err != nil {
t.Fatal(err)
Expand Down
6 changes: 3 additions & 3 deletions level/benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ func Benchmark(b *testing.B) {
return l
}},
{"TimeContext", func(l log.Logger) log.Logger {
return log.NewContext(l).With("time", log.DefaultTimestampUTC)
return log.With(l, "time", log.DefaultTimestampUTC)
}},
{"CallerContext", func(l log.Logger) log.Logger {
return log.NewContext(l).With("caller", log.DefaultCaller)
return log.With(l, "caller", log.DefaultCaller)
}},
{"TimeCallerReqIDContext", func(l log.Logger) log.Logger {
return log.NewContext(l).With("time", log.DefaultTimestampUTC, "caller", log.DefaultCaller, "reqID", 29)
return log.With(l, "time", log.DefaultTimestampUTC, "caller", log.DefaultCaller, "reqID", 29)
}},
}

Expand Down
2 changes: 1 addition & 1 deletion level/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ func Example_basic() {
// setup logger with level filter
logger := log.NewLogfmtLogger(os.Stdout)
logger = level.NewFilter(logger, level.AllowInfo())
logger = log.NewContext(logger).With("caller", log.DefaultCaller)
logger = log.With(logger, "caller", log.DefaultCaller)

// use level helpers to log at different levels
level.Error(logger).Log("err", errors.New("bad data"))
Expand Down
8 changes: 4 additions & 4 deletions level/level.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,22 @@ import "github.com/go-kit/kit/log"

// Error returns a logger that includes a Key/ErrorValue pair.
func Error(logger log.Logger) log.Logger {
return log.NewContext(logger).WithPrefix(Key(), ErrorValue())
return log.WithPrefix(logger, Key(), ErrorValue())
}

// Warn returns a logger that includes a Key/WarnValue pair.
func Warn(logger log.Logger) log.Logger {
return log.NewContext(logger).WithPrefix(Key(), WarnValue())
return log.WithPrefix(logger, Key(), WarnValue())
}

// Info returns a logger that includes a Key/InfoValue pair.
func Info(logger log.Logger) log.Logger {
return log.NewContext(logger).WithPrefix(Key(), InfoValue())
return log.WithPrefix(logger, Key(), InfoValue())
}

// Debug returns a logger that includes a Key/DebugValue pair.
func Debug(logger log.Logger) log.Logger {
return log.NewContext(logger).WithPrefix(Key(), DebugValue())
return log.WithPrefix(logger, Key(), DebugValue())
}

// NewFilter wraps next and implements level filtering. See the commentary on
Expand Down
4 changes: 2 additions & 2 deletions level/level_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ func TestLevelContext(t *testing.T) {
var logger log.Logger
logger = log.NewLogfmtLogger(&buf)
logger = level.NewFilter(logger, level.AllowAll())
logger = log.NewContext(logger).With("caller", log.DefaultCaller)
logger = log.With(logger, "caller", log.DefaultCaller)

level.Info(logger).Log("foo", "bar")
if want, have := `level=info caller=level_test.go:149 foo=bar`, strings.TrimSpace(buf.String()); want != have {
Expand All @@ -159,7 +159,7 @@ func TestContextLevel(t *testing.T) {
// to specify a higher callstack depth value.
var logger log.Logger
logger = log.NewLogfmtLogger(&buf)
logger = log.NewContext(logger).With("caller", log.Caller(5))
logger = log.With(logger, "caller", log.Caller(5))
logger = level.NewFilter(logger, level.AllowAll())

level.Info(logger).Log("foo", "bar")
Expand Down
34 changes: 18 additions & 16 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ type Logger interface {
// the missing value.
var ErrMissingValue = errors.New("(MISSING)")

// NewContext returns a new Context that logs to logger.
func NewContext(logger Logger) *Context {
if c, ok := logger.(*Context); ok {
// newContext returns a new context that logs to logger.
func newContext(logger Logger) *context {
if c, ok := logger.(*context); ok {
return c
}
return &Context{logger: logger}
return &context{logger: logger}
}

// Context must always have the same number of stack frames between calls to
Expand Down Expand Up @@ -57,11 +57,11 @@ func NewContext(logger Logger) *Context {
// Context.Log through a variable with type Context. Using pointer receivers
// avoids this problem.

// A Context wraps a Logger and holds keyvals that it includes in all log
// events. When logging, a Context replaces all value elements (odd indexes)
// A context wraps a Logger and holds keyvals that it includes in all log
// events. When logging, a context replaces all value elements (odd indexes)
// containing a Valuer with their generated value for each call to its Log
// method.
type Context struct {
type context struct {
logger Logger
keyvals []interface{}
hasValuer bool
Expand All @@ -70,7 +70,7 @@ type Context struct {
// Log replaces all value elements (odd indexes) containing a Valuer in the
// stored context with their generated value, appends keyvals, and passes the
// result to the wrapped Logger.
func (l *Context) Log(keyvals ...interface{}) error {
func (l *context) Log(keyvals ...interface{}) error {
kvs := append(l.keyvals, keyvals...)
if len(kvs)%2 != 0 {
kvs = append(kvs, ErrMissingValue)
Expand All @@ -86,16 +86,17 @@ func (l *Context) Log(keyvals ...interface{}) error {
return l.logger.Log(kvs...)
}

// With returns a new Context with keyvals appended to those of the receiver.
func (l *Context) With(keyvals ...interface{}) *Context {
// With returns a new context with keyvals appended to those of the receiver.
func With(logger Logger, keyvals ...interface{}) Logger {
if len(keyvals) == 0 {
return l
return logger
}
l := newContext(logger)
kvs := append(l.keyvals, keyvals...)
if len(kvs)%2 != 0 {
kvs = append(kvs, ErrMissingValue)
}
return &Context{
return &context{
logger: l.logger,
// Limiting the capacity of the stored keyvals ensures that a new
// backing array is created if the slice must grow in Log or With.
Expand All @@ -106,12 +107,13 @@ func (l *Context) With(keyvals ...interface{}) *Context {
}
}

// WithPrefix returns a new Context with keyvals prepended to those of the
// WithPrefix returns a new context with keyvals prepended to those of the
// receiver.
func (l *Context) WithPrefix(keyvals ...interface{}) *Context {
func WithPrefix(logger Logger, keyvals ...interface{}) Logger {
if len(keyvals) == 0 {
return l
return logger
}
l := newContext(logger)
// Limiting the capacity of the stored keyvals ensures that a new
// backing array is created if the slice must grow in Log or With.
// Using the extra capacity without copying risks a data race that
Expand All @@ -126,7 +128,7 @@ func (l *Context) WithPrefix(keyvals ...interface{}) *Context {
kvs = append(kvs, ErrMissingValue)
}
kvs = append(kvs, l.keyvals...)
return &Context{
return &context{
logger: l.logger,
keyvals: kvs,
hasValuer: l.hasValuer || containsValuer(keyvals),
Expand Down
Loading

0 comments on commit d4d0b60

Please sign in to comment.