gitlab.com/gitlab-org/labkit@v1.21.0/log/access_logger_options.go (about)

     1  package log
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/sirupsen/logrus"
     7  )
     8  
     9  // ExtraFieldsGeneratorFunc allows extra fields to be included in the access log.
    10  type ExtraFieldsGeneratorFunc func(r *http.Request) Fields
    11  
    12  // XFFAllowedFunc decides whether X-Forwarded-For headers are to be trusted.
    13  type XFFAllowedFunc func(ip string) bool
    14  
    15  // The configuration for an access logger.
    16  type accessLoggerConfig struct {
    17  	logger      *logrus.Logger
    18  	extraFields ExtraFieldsGeneratorFunc
    19  	fields      AccessLogField
    20  	xffAllowed  XFFAllowedFunc
    21  }
    22  
    23  func nullExtraFieldsGenerator(r *http.Request) Fields {
    24  	return Fields{}
    25  }
    26  
    27  // AccessLoggerOption will configure a access logger handler.
    28  type AccessLoggerOption func(*accessLoggerConfig)
    29  
    30  func applyAccessLoggerOptions(opts []AccessLoggerOption) accessLoggerConfig {
    31  	config := accessLoggerConfig{
    32  		logger:      logger,
    33  		extraFields: nullExtraFieldsGenerator,
    34  		fields:      defaultEnabledFields,
    35  		xffAllowed:  func(sip string) bool { return true },
    36  	}
    37  	for _, v := range opts {
    38  		v(&config)
    39  	}
    40  
    41  	return config
    42  }
    43  
    44  // WithExtraFields allows extra fields to be passed into the access logger, based on the request.
    45  func WithExtraFields(f ExtraFieldsGeneratorFunc) AccessLoggerOption {
    46  	return func(config *accessLoggerConfig) {
    47  		config.extraFields = f
    48  	}
    49  }
    50  
    51  // WithFieldsExcluded allows fields to be excluded from the access log. For example, backend services may not require the referer or user agent fields.
    52  func WithFieldsExcluded(fields AccessLogField) AccessLoggerOption {
    53  	return func(config *accessLoggerConfig) {
    54  		config.fields &^= fields
    55  	}
    56  }
    57  
    58  // WithAccessLogger configures the logger to be used with the access logger.
    59  func WithAccessLogger(logger *logrus.Logger) AccessLoggerOption {
    60  	return func(config *accessLoggerConfig) {
    61  		config.logger = logger
    62  	}
    63  }
    64  
    65  // WithXFFAllowed decides whether to trust X-Forwarded-For headers.
    66  func WithXFFAllowed(xffAllowed XFFAllowedFunc) AccessLoggerOption {
    67  	return func(config *accessLoggerConfig) {
    68  		config.xffAllowed = xffAllowed
    69  	}
    70  }