Codebase list golang-github-go-kit-kit / 57c8678
Give meaning to the zero value and handle wrapping a nil logger. Chris Hines 8 years ago
2 changed file(s) with 18 addition(s) and 3 deletion(s). Raw diff Collapse all Expand all
6161 }
6262
6363 // SwapLogger wraps another logger that may be safely replaced while other
64 // goroutines use the SwapLogger concurrently.
64 // goroutines use the SwapLogger concurrently. An uninitialized SwapLogger
65 // will discard all log events without error.
6566 type SwapLogger struct {
6667 logger atomic.Value
6768 }
7879 }
7980
8081 // Log implements the Logger interface by calling Log on the currently wrapped
81 // logger.
82 // logger. It does not log anything if the wrapped logger is nil.
8283 func (l *SwapLogger) Log(keyvals ...interface{}) error {
83 return l.logger.Load().(loggerStruct).Log(keyvals...)
84 s := l.logger.Load().(loggerStruct)
85 if s.Logger == nil {
86 return nil
87 }
88 return s.Log(keyvals...)
8489 }
8590
8691 // Swap replaces the currently wrapped logger with logger. Swap may be called
133133 if got, want := buf.String(), "k=v\n"; got != want {
134134 t.Errorf("got %v, want %v", got, want)
135135 }
136
137 buf.Reset()
138 logger.Swap(nil)
139
140 if err := logger.Log("k", "v"); err != nil {
141 t.Error(err)
142 }
143 if got, want := buf.String(), ""; got != want {
144 t.Errorf("got %v, want %v", got, want)
145 }
136146 }
137147
138148 func TestSwapLoggerConcurrency(t *testing.T) {