...

Source file src/github.com/rs/zerolog/ctx.go

Documentation: github.com/rs/zerolog

     1  package zerolog
     2  
     3  import (
     4  	"context"
     5  )
     6  
     7  var disabledLogger *Logger
     8  
     9  func init() {
    10  	SetGlobalLevel(TraceLevel)
    11  	l := Nop()
    12  	disabledLogger = &l
    13  }
    14  
    15  type ctxKey struct{}
    16  
    17  // WithContext returns a copy of ctx with l associated. If an instance of Logger
    18  // is already in the context, the context is not updated.
    19  //
    20  // For instance, to add a field to an existing logger in the context, use this
    21  // notation:
    22  //
    23  //     ctx := r.Context()
    24  //     l := zerolog.Ctx(ctx)
    25  //     l.UpdateContext(func(c Context) Context {
    26  //         return c.Str("bar", "baz")
    27  //     })
    28  func (l Logger) WithContext(ctx context.Context) context.Context {
    29  	if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok {
    30  		if lp == &l {
    31  			// Do not store same logger.
    32  			return ctx
    33  		}
    34  	} else if l.level == Disabled {
    35  		// Do not store disabled logger.
    36  		return ctx
    37  	}
    38  	return context.WithValue(ctx, ctxKey{}, &l)
    39  }
    40  
    41  // Ctx returns the Logger associated with the ctx. If no logger
    42  // is associated, DefaultContextLogger is returned, unless DefaultContextLogger
    43  // is nil, in which case a disabled logger is returned.
    44  func Ctx(ctx context.Context) *Logger {
    45  	if l, ok := ctx.Value(ctxKey{}).(*Logger); ok {
    46  		return l
    47  	} else if l = DefaultContextLogger; l != nil {
    48  		return l
    49  	}
    50  	return disabledLogger
    51  }
    52  

View as plain text