1package log
2
3import (
4	"net/http"
5
6	"github.com/sirupsen/logrus"
7)
8
9// ExtraFieldsGeneratorFunc allows extra fields to be included in the access log.
10type ExtraFieldsGeneratorFunc func(r *http.Request) Fields
11
12// XFFAllowedFunc decides whether X-Forwarded-For headers are to be trusted.
13type XFFAllowedFunc func(ip string) bool
14
15// The configuration for an access logger.
16type accessLoggerConfig struct {
17	logger      *logrus.Logger
18	extraFields ExtraFieldsGeneratorFunc
19	fields      AccessLogField
20	xffAllowed  XFFAllowedFunc
21}
22
23func nullExtraFieldsGenerator(r *http.Request) Fields {
24	return Fields{}
25}
26
27// AccessLoggerOption will configure a access logger handler.
28type AccessLoggerOption func(*accessLoggerConfig)
29
30func 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.
45func 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.
52func 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.
59func 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.
66func WithXFFAllowed(xffAllowed XFFAllowedFunc) AccessLoggerOption {
67	return func(config *accessLoggerConfig) {
68		config.xffAllowed = xffAllowed
69	}
70}
71