knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/logging/logger.go (about)

     1  /*
     2  Copyright 2018 The Knative Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package logging
    18  
    19  import (
    20  	"context"
    21  
    22  	"go.uber.org/zap"
    23  )
    24  
    25  type loggerKey struct{}
    26  
    27  // This logger is used when there is no logger attached to the context.
    28  // Rather than returning nil and causing a panic, we will use the fallback
    29  // logger. Fallback logger is tagged with logger=fallback to make sure
    30  // that code that doesn't set the logger correctly can be caught at runtime.
    31  var fallbackLogger *zap.SugaredLogger
    32  
    33  func init() {
    34  	if logger, err := zap.NewProduction(); err != nil {
    35  		// We failed to create a fallback logger. Our fallback
    36  		// unfortunately falls back to noop.
    37  		fallbackLogger = zap.NewNop().Sugar()
    38  	} else {
    39  		fallbackLogger = logger.Named("fallback").Sugar()
    40  	}
    41  }
    42  
    43  // WithLogger returns a copy of parent context in which the
    44  // value associated with logger key is the supplied logger.
    45  func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context {
    46  	return context.WithValue(ctx, loggerKey{}, logger)
    47  }
    48  
    49  // FromContext returns the logger stored in context.
    50  // Returns nil if no logger is set in context, or if the stored value is
    51  // not of correct type.
    52  func FromContext(ctx context.Context) *zap.SugaredLogger {
    53  	if logger, ok := ctx.Value(loggerKey{}).(*zap.SugaredLogger); ok {
    54  		return logger
    55  	}
    56  	return fallbackLogger
    57  }