github.com/containerd/containerd@v22.0.0-20200918172823-438c87b8e050+incompatible/log/context.go (about)

     1  /*
     2     Copyright The containerd 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 log
    18  
    19  import (
    20  	"context"
    21  
    22  	"github.com/sirupsen/logrus"
    23  )
    24  
    25  var (
    26  	// G is an alias for GetLogger.
    27  	//
    28  	// We may want to define this locally to a package to get package tagged log
    29  	// messages.
    30  	G = GetLogger
    31  
    32  	// L is an alias for the standard logger.
    33  	L = logrus.NewEntry(logrus.StandardLogger())
    34  )
    35  
    36  type (
    37  	loggerKey struct{}
    38  )
    39  
    40  // RFC3339NanoFixed is time.RFC3339Nano with nanoseconds padded using zeros to
    41  // ensure the formatted time is always the same number of characters.
    42  const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
    43  
    44  // WithLogger returns a new context with the provided logger. Use in
    45  // combination with logger.WithField(s) for great effect.
    46  func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context {
    47  	return context.WithValue(ctx, loggerKey{}, logger)
    48  }
    49  
    50  // GetLogger retrieves the current logger from the context. If no logger is
    51  // available, the default logger is returned.
    52  func GetLogger(ctx context.Context) *logrus.Entry {
    53  	logger := ctx.Value(loggerKey{})
    54  
    55  	if logger == nil {
    56  		return L
    57  	}
    58  
    59  	return logger.(*logrus.Entry)
    60  }