github.com/freiheit-com/kuberpult@v1.24.2-0.20240328135542-315d5630abe6/pkg/logger/logger.go (about)

     1  /*This file is part of kuberpult.
     2  
     3  Kuberpult is free software: you can redistribute it and/or modify
     4  it under the terms of the Expat(MIT) License as published by
     5  the Free Software Foundation.
     6  
     7  Kuberpult is distributed in the hope that it will be useful,
     8  but WITHOUT ANY WARRANTY; without even the implied warranty of
     9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    10  MIT License for more details.
    11  
    12  You should have received a copy of the MIT License
    13  along with kuberpult. If not, see <https://directory.fsf.org/wiki/License:Expat>.
    14  
    15  Copyright 2023 freiheit.com*/
    16  
    17  // Log implementation for all microservices in the project.
    18  // Log functions can be called through the convenience interfaces
    19  // logger.Debugf(), logger.Errorf(), logger.Panicf()
    20  //
    21  // Deliberately reduces the interface to only Debugf, Errorf and Panicf.
    22  // The other log levels are discouraged (see fdc Software Engineering Standards
    23  // for details)
    24  package logger
    25  
    26  import (
    27  	"context"
    28  	"fmt"
    29  	"os"
    30  
    31  	"github.com/blendle/zapdriver"
    32  	"github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap"
    33  	"go.uber.org/zap"
    34  	"go.uber.org/zap/zapcore"
    35  )
    36  
    37  func FromContext(ctx context.Context) *zap.Logger {
    38  	return ctxzap.Extract(ctx)
    39  }
    40  
    41  func WithLogger(ctx context.Context, logger *zap.Logger) context.Context {
    42  	return ctxzap.ToContext(ctx, logger)
    43  }
    44  
    45  func Wrap(ctx context.Context, inner func(ctx context.Context) error) error {
    46  	format := os.Getenv("LOG_FORMAT")
    47  	envLevel := os.Getenv("LOG_LEVEL")
    48  	var (
    49  		logger *zap.Logger
    50  		level  zapcore.Level = zapcore.WarnLevel
    51  		err    error
    52  	)
    53  	if envLevel != "" {
    54  		err = level.Set(envLevel)
    55  		if err != nil {
    56  			return err
    57  		}
    58  	}
    59  	options := []zap.Option{zap.IncreaseLevel(level)}
    60  	switch format {
    61  	case "gcp":
    62  		logger, err = zapdriver.NewProduction(options...)
    63  	case "", "default":
    64  		logger, err = zap.NewProduction(options...)
    65  	default:
    66  		return fmt.Errorf("unknown log_format: %s", format)
    67  	}
    68  	if err != nil {
    69  		return err
    70  	}
    71  	defer func() {
    72  		syncErr := logger.Sync()
    73  		if err == nil {
    74  			err = syncErr
    75  		}
    76  	}()
    77  	err = inner(WithLogger(ctx, logger))
    78  
    79  	return err
    80  }