...

Source file src/github.com/sigstore/timestamp-authority/pkg/log/log.go

Documentation: github.com/sigstore/timestamp-authority/pkg/log

     1  //
     2  // Copyright 2022 The Sigstore 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  package log
    17  
    18  import (
    19  	"context"
    20  	"log"
    21  	"net/http"
    22  
    23  	"github.com/go-chi/chi/middleware"
    24  	"go.uber.org/zap"
    25  	"go.uber.org/zap/zapcore"
    26  )
    27  
    28  // Logger set the default logger to development mode
    29  var Logger *zap.SugaredLogger
    30  
    31  func init() {
    32  	ConfigureLogger("dev")
    33  }
    34  
    35  func ConfigureLogger(logType string) {
    36  	var cfg zap.Config
    37  	if logType == "prod" {
    38  		cfg = zap.NewProductionConfig()
    39  		cfg.EncoderConfig.LevelKey = "severity"
    40  		cfg.EncoderConfig.MessageKey = "message"
    41  	} else {
    42  		cfg = zap.NewDevelopmentConfig()
    43  		cfg.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
    44  	}
    45  	logger, err := cfg.Build()
    46  	if err != nil {
    47  		log.Fatalln("createLogger", err)
    48  	}
    49  	Logger = logger.Sugar()
    50  }
    51  
    52  var CliLogger = createCliLogger()
    53  
    54  func createCliLogger() *zap.SugaredLogger {
    55  	cfg := zap.NewDevelopmentConfig()
    56  	cfg.EncoderConfig.TimeKey = ""
    57  	cfg.EncoderConfig.LevelKey = ""
    58  	cfg.DisableCaller = true
    59  	cfg.DisableStacktrace = true
    60  	logger, err := cfg.Build()
    61  	if err != nil {
    62  		log.Fatalln("createLogger", err)
    63  	}
    64  
    65  	return logger.Sugar()
    66  }
    67  
    68  func WithRequestID(ctx context.Context, id string) context.Context {
    69  	return context.WithValue(ctx, middleware.RequestIDKey, id)
    70  }
    71  
    72  func RequestIDLogger(r *http.Request) *zap.SugaredLogger {
    73  	proposedLogger := Logger
    74  	if r != nil {
    75  		if ctxRequestID, ok := r.Context().Value(middleware.RequestIDKey).(string); ok {
    76  			proposedLogger = proposedLogger.With(zap.String("requestID", ctxRequestID))
    77  		}
    78  	}
    79  	return proposedLogger
    80  }
    81  

View as plain text