diff --git a/integration/access_log_test.go b/integration/access_log_test.go index ea21fe500..0e0aa925d 100644 --- a/integration/access_log_test.go +++ b/integration/access_log_test.go @@ -46,7 +46,7 @@ func (s *AccessLogSuite) SetUpSuite(c *check.C) { func (s *AccessLogSuite) TearDownTest(c *check.C) { displayTraefikLogFile(c, traefikTestLogFile) - os.Remove(traefikTestAccessLogFile) + _ = os.Remove(traefikTestAccessLogFile) } func (s *AccessLogSuite) TestAccessLog(c *check.C) { @@ -59,7 +59,7 @@ func (s *AccessLogSuite) TestAccessLog(c *check.C) { defer func() { traefikLog, err := ioutil.ReadFile(traefikTestLogFile) c.Assert(err, checker.IsNil) - log.Info(string(traefikLog)) + log.WithoutContext().Info(string(traefikLog)) }() err := cmd.Start() @@ -233,7 +233,7 @@ func digestParts(resp *http.Response) map[string]string { func getMD5(data string) string { digest := md5.New() if _, err := digest.Write([]byte(data)); err != nil { - log.Error(err) + log.WithoutContext().Error(err) } return fmt.Sprintf("%x", digest.Sum(nil)) } @@ -241,7 +241,7 @@ func getMD5(data string) string { func getCnonce() string { b := make([]byte, 8) if _, err := io.ReadFull(rand.Reader, b); err != nil { - log.Error(err) + log.WithoutContext().Error(err) } return fmt.Sprintf("%x", b)[:16] } diff --git a/integration/fake_dns_server.go b/integration/fake_dns_server.go index 1c4c7a6cd..afae6fe3d 100644 --- a/integration/fake_dns_server.go +++ b/integration/fake_dns_server.go @@ -15,6 +15,8 @@ type handler struct{} // Simplified version of the Challenge Test Server from Boulder // https://github.com/letsencrypt/boulder/blob/a6597b9f120207eff192c3e4107a7e49972a0250/test/challtestsrv/dnsone.go#L40 func (s *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) { + logger := log.WithoutContext() + m := new(dns.Msg) m.SetReply(r) m.Compress = false @@ -23,8 +25,9 @@ func (s *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) { if fakeDNS == "" { fakeDNS = "127.0.0.1" } + for _, q := range r.Question { - log.Infof("Query -- [%s] %s", q.Name, dns.TypeToString[q.Qtype]) + logger.Infof("Query -- [%s] %s", q.Name, dns.TypeToString[q.Qtype]) switch q.Qtype { case dns.TypeA: @@ -94,7 +97,7 @@ func (s *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) { m.Ns = append(m.Ns, auth) if err := w.WriteMsg(m); err != nil { - log.Fatalf("Failed to write message %v", err) + logger.Fatalf("Failed to write message %v", err) } } @@ -106,9 +109,9 @@ func startFakeDNSServer() *dns.Server { } go func() { - log.Infof("Start a fake DNS server.") + log.WithoutContext().Infof("Start a fake DNS server.") if err := srv.ListenAndServe(); err != nil { - log.Fatalf("Failed to set udp listener %v", err) + log.WithoutContext().Fatalf("Failed to set udp listener %v", err) } }() diff --git a/integration/grpc_test.go b/integration/grpc_test.go index 7664c4548..d79ed0009 100644 --- a/integration/grpc_test.go +++ b/integration/grpc_test.go @@ -50,7 +50,7 @@ func (s *myserver) StreamExample(in *helloworld.StreamExampleRequest, server hel } if err := server.Send(&helloworld.StreamExampleReply{Data: string(data)}); err != nil { - log.Error(err) + log.WithoutContext().Error(err) } <-s.stopStreamExample diff --git a/integration/integration_test.go b/integration/integration_test.go index 47f5f0b4f..daca739d5 100644 --- a/integration/integration_test.go +++ b/integration/integration_test.go @@ -28,7 +28,7 @@ var showLog = flag.Bool("tlog", false, "always show Traefik logs") func Test(t *testing.T) { if !*integration { - log.Info("Integration tests disabled.") + log.WithoutContext().Info("Integration tests disabled.") return } @@ -91,7 +91,7 @@ func (s *BaseSuite) createComposeProject(c *check.C, name string) { ip, _, err := net.ParseCIDR(addr.String()) c.Assert(err, checker.IsNil) if !ip.IsLoopback() && ip.To4() != nil { - os.Setenv("DOCKER_HOST_IP", ip.String()) + _ = os.Setenv("DOCKER_HOST_IP", ip.String()) break } } diff --git a/pkg/collector/collector.go b/pkg/collector/collector.go index 4a1a6f2a5..6493859a0 100644 --- a/pkg/collector/collector.go +++ b/pkg/collector/collector.go @@ -35,7 +35,7 @@ func Collect(staticConfiguration *static.Configuration) error { return err } - log.Infof("Anonymous stats sent to %s: %s", collectorURL, anonConfig) + log.WithoutContext().Infof("Anonymous stats sent to %s: %s", collectorURL, anonConfig) hashConf, err := hashstructure.Hash(staticConfiguration, nil) if err != nil { diff --git a/pkg/config/static/static_config.go b/pkg/config/static/static_config.go index f7caa20cc..38b3569bb 100644 --- a/pkg/config/static/static_config.go +++ b/pkg/config/static/static_config.go @@ -238,13 +238,15 @@ func getSafeACMECAServer(caServerSrc string) string { if strings.HasPrefix(caServerSrc, "https://acme-v01.api.letsencrypt.org") { caServer := strings.Replace(caServerSrc, "v01", "v02", 1) - log.Warnf("The CA server %[1]q refers to a v01 endpoint of the ACME API, please change to %[2]q. Fallback to %[2]q.", caServerSrc, caServer) + log.WithoutContext(). + Warnf("The CA server %[1]q refers to a v01 endpoint of the ACME API, please change to %[2]q. Fallback to %[2]q.", caServerSrc, caServer) return caServer } if strings.HasPrefix(caServerSrc, "https://acme-staging.api.letsencrypt.org") { caServer := strings.Replace(caServerSrc, "https://acme-staging.api.letsencrypt.org", "https://acme-staging-v02.api.letsencrypt.org", 1) - log.Warnf("The CA server %[1]q refers to a v01 endpoint of the ACME API, please change to %[2]q. Fallback to %[2]q.", caServerSrc, caServer) + log.WithoutContext(). + Warnf("The CA server %[1]q refers to a v01 endpoint of the ACME API, please change to %[2]q. Fallback to %[2]q.", caServerSrc, caServer) return caServer } diff --git a/pkg/healthcheck/healthcheck.go b/pkg/healthcheck/healthcheck.go index 0e5ff0de7..c1385c399 100644 --- a/pkg/healthcheck/healthcheck.go +++ b/pkg/healthcheck/healthcheck.go @@ -122,37 +122,41 @@ func (hc *HealthCheck) SetBackendsConfiguration(parentCtx context.Context, backe } func (hc *HealthCheck) execute(ctx context.Context, backend *BackendConfig) { - log.Debugf("Initial health check for backend: %q", backend.name) - hc.checkBackend(backend) + logger := log.FromContext(ctx) + logger.Debugf("Initial health check for backend: %q", backend.name) + + hc.checkBackend(ctx, backend) ticker := time.NewTicker(backend.Interval) defer ticker.Stop() for { select { case <-ctx.Done(): - log.Debugf("Stopping current health check goroutines of backend: %s", backend.name) + logger.Debugf("Stopping current health check goroutines of backend: %s", backend.name) return case <-ticker.C: - log.Debugf("Refreshing health check for backend: %s", backend.name) - hc.checkBackend(backend) + logger.Debugf("Refreshing health check for backend: %s", backend.name) + hc.checkBackend(ctx, backend) } } } -func (hc *HealthCheck) checkBackend(backend *BackendConfig) { +func (hc *HealthCheck) checkBackend(ctx context.Context, backend *BackendConfig) { + logger := log.FromContext(ctx) + enabledURLs := backend.LB.Servers() var newDisabledURLs []backendURL // FIXME re enable metrics for _, disableURL := range backend.disabledURLs { // FIXME serverUpMetricValue := float64(0) if err := checkHealth(disableURL.url, backend); err == nil { - log.Warnf("Health check up: Returning to server list. Backend: %q URL: %q Weight: %d", + logger.Warnf("Health check up: Returning to server list. Backend: %q URL: %q Weight: %d", backend.name, disableURL.url.String(), disableURL.weight) if err = backend.LB.UpsertServer(disableURL.url, roundrobin.Weight(disableURL.weight)); err != nil { - log.Error(err) + logger.Error(err) } // FIXME serverUpMetricValue = 1 } else { - log.Warnf("Health check still failing. Backend: %q URL: %q Reason: %s", backend.name, disableURL.url.String(), err) + logger.Warnf("Health check still failing. Backend: %q URL: %q Reason: %s", backend.name, disableURL.url.String(), err) newDisabledURLs = append(newDisabledURLs, disableURL) } // FIXME labelValues := []string{"backend", backend.name, "url", backendurl.url.String()} @@ -173,9 +177,9 @@ func (hc *HealthCheck) checkBackend(backend *BackendConfig) { weight = 1 } } - log.Warnf("Health check failed: Remove from server list. Backend: %q URL: %q Weight: %d Reason: %s", backend.name, enableURL.String(), weight, err) + logger.Warnf("Health check failed: Remove from server list. Backend: %q URL: %q Weight: %d Reason: %s", backend.name, enableURL.String(), weight, err) if err := backend.LB.RemoveServer(enableURL); err != nil { - log.Error(err) + logger.Error(err) } backend.disabledURLs = append(backend.disabledURLs, backendURL{enableURL, weight}) // FIXME serverUpMetricValue = 0 @@ -244,10 +248,10 @@ func checkHealth(serverURL *url.URL, backend *BackendConfig) error { } // NewLBStatusUpdater returns a new LbStatusUpdater -func NewLBStatusUpdater(bh BalancerHandler, svinfo *runtime.ServiceInfo) *LbStatusUpdater { +func NewLBStatusUpdater(bh BalancerHandler, info *runtime.ServiceInfo) *LbStatusUpdater { return &LbStatusUpdater{ BalancerHandler: bh, - serviceInfo: svinfo, + serviceInfo: info, } } diff --git a/pkg/log/deprecated.go b/pkg/log/deprecated.go index 7c7f573b3..2bdf735ed 100644 --- a/pkg/log/deprecated.go +++ b/pkg/log/deprecated.go @@ -62,12 +62,6 @@ func Panic(args ...interface{}) { mainLogger.Panic(args...) } -// Panicf logs a message at level Panic on the standard logger. -// Deprecated -func Panicf(format string, args ...interface{}) { - mainLogger.Panicf(format, args...) -} - // Fatal logs a message at level Fatal on the standard logger. // Deprecated func Fatal(args ...interface{}) { diff --git a/pkg/log/fields.go b/pkg/log/fields.go index 97e51412d..f84b00498 100644 --- a/pkg/log/fields.go +++ b/pkg/log/fields.go @@ -12,4 +12,5 @@ const ( MetricsProviderName = "metricsProviderName" TracingProviderName = "tracingProviderName" ServerName = "serverName" + TLSStoreName = "tlsStoreName" ) diff --git a/pkg/middlewares/addprefix/add_prefix.go b/pkg/middlewares/addprefix/add_prefix.go index 02374ea89..655e874a8 100644 --- a/pkg/middlewares/addprefix/add_prefix.go +++ b/pkg/middlewares/addprefix/add_prefix.go @@ -6,6 +6,7 @@ import ( "net/http" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" @@ -24,7 +25,7 @@ type addPrefix struct { // New creates a new handler. func New(ctx context.Context, next http.Handler, config dynamic.AddPrefix, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") var result *addPrefix if len(config.Prefix) > 0 { @@ -45,7 +46,7 @@ func (ap *addPrefix) GetTracingInformation() (string, ext.SpanKindEnum) { } func (ap *addPrefix) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - logger := middlewares.GetLogger(req.Context(), ap.name, typeName) + logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), ap.name, typeName)) oldURLPath := req.URL.Path req.URL.Path = ap.prefix + req.URL.Path diff --git a/pkg/middlewares/auth/basic_auth.go b/pkg/middlewares/auth/basic_auth.go index 62eca1cb9..ee857d05a 100644 --- a/pkg/middlewares/auth/basic_auth.go +++ b/pkg/middlewares/auth/basic_auth.go @@ -9,6 +9,7 @@ import ( goauth "github.com/abbot/go-http-auth" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/middlewares/accesslog" "github.com/containous/traefik/v2/pkg/tracing" @@ -30,7 +31,7 @@ type basicAuth struct { // NewBasic creates a basicAuth middleware. func NewBasic(ctx context.Context, next http.Handler, authConfig dynamic.BasicAuth, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, basicTypeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, basicTypeName)).Debug("Creating middleware") users, err := getUsers(authConfig.UsersFile, authConfig.Users, basicUserParser) if err != nil { return nil, err @@ -58,7 +59,7 @@ func (b *basicAuth) GetTracingInformation() (string, ext.SpanKindEnum) { } func (b *basicAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - logger := middlewares.GetLogger(req.Context(), b.name, basicTypeName) + logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), b.name, basicTypeName)) if username := b.auth.CheckAuth(req); username == "" { logger.Debug("Authentication failed") diff --git a/pkg/middlewares/auth/digest_auth.go b/pkg/middlewares/auth/digest_auth.go index 25cb29cda..0a43d45c1 100644 --- a/pkg/middlewares/auth/digest_auth.go +++ b/pkg/middlewares/auth/digest_auth.go @@ -9,6 +9,7 @@ import ( goauth "github.com/abbot/go-http-auth" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/middlewares/accesslog" "github.com/containous/traefik/v2/pkg/tracing" @@ -30,7 +31,7 @@ type digestAuth struct { // NewDigest creates a digest auth middleware. func NewDigest(ctx context.Context, next http.Handler, authConfig dynamic.DigestAuth, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, digestTypeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, digestTypeName)).Debug("Creating middleware") users, err := getUsers(authConfig.UsersFile, authConfig.Users, digestUserParser) if err != nil { return nil, err @@ -58,7 +59,7 @@ func (d *digestAuth) GetTracingInformation() (string, ext.SpanKindEnum) { } func (d *digestAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - logger := middlewares.GetLogger(req.Context(), d.name, digestTypeName) + logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), d.name, digestTypeName)) if username, _ := d.auth.CheckAuth(req); username == "" { logger.Debug("Digest authentication failed") diff --git a/pkg/middlewares/auth/forward.go b/pkg/middlewares/auth/forward.go index 85891f76e..f1b4421bf 100644 --- a/pkg/middlewares/auth/forward.go +++ b/pkg/middlewares/auth/forward.go @@ -10,6 +10,7 @@ import ( "strings" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" @@ -34,7 +35,7 @@ type forwardAuth struct { // NewForward creates a forward auth middleware. func NewForward(ctx context.Context, next http.Handler, config dynamic.ForwardAuth, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, forwardedTypeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, forwardedTypeName)).Debug("Creating middleware") fa := &forwardAuth{ address: config.Address, @@ -61,7 +62,7 @@ func (fa *forwardAuth) GetTracingInformation() (string, ext.SpanKindEnum) { } func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - logger := middlewares.GetLogger(req.Context(), fa.name, forwardedTypeName) + logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), fa.name, forwardedTypeName)) // Ensure our request client does not follow redirects httpClient := http.Client{ diff --git a/pkg/middlewares/buffering/buffering.go b/pkg/middlewares/buffering/buffering.go index e6183a723..069e710a7 100644 --- a/pkg/middlewares/buffering/buffering.go +++ b/pkg/middlewares/buffering/buffering.go @@ -5,6 +5,7 @@ import ( "net/http" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" @@ -22,7 +23,7 @@ type buffer struct { // New creates a buffering middleware. func New(ctx context.Context, next http.Handler, config dynamic.Buffering, name string) (http.Handler, error) { - logger := middlewares.GetLogger(ctx, name, typeName) + logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)) logger.Debug("Creating middleware") logger.Debugf("Setting up buffering: request limits: %d (mem), %d (max), response limits: %d (mem), %d (max) with retry: '%s'", config.MemRequestBodyBytes, config.MaxRequestBodyBytes, config.MemResponseBodyBytes, config.MaxResponseBodyBytes, config.RetryExpression) diff --git a/pkg/middlewares/chain/chain.go b/pkg/middlewares/chain/chain.go index ee3668bbd..bf227b069 100644 --- a/pkg/middlewares/chain/chain.go +++ b/pkg/middlewares/chain/chain.go @@ -6,6 +6,7 @@ import ( "github.com/containous/alice" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" ) @@ -19,7 +20,7 @@ type chainBuilder interface { // New creates a chain middleware func New(ctx context.Context, next http.Handler, config dynamic.Chain, builder chainBuilder, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") middlewareChain := builder.BuildChain(ctx, config.Middlewares) return middlewareChain.Then(next) diff --git a/pkg/middlewares/circuitbreaker/circuit_breaker.go b/pkg/middlewares/circuitbreaker/circuit_breaker.go index dc561b465..c4c2c5cf1 100644 --- a/pkg/middlewares/circuitbreaker/circuit_breaker.go +++ b/pkg/middlewares/circuitbreaker/circuit_breaker.go @@ -25,7 +25,7 @@ type circuitBreaker struct { func New(ctx context.Context, next http.Handler, confCircuitBreaker dynamic.CircuitBreaker, name string) (http.Handler, error) { expression := confCircuitBreaker.Expression - logger := middlewares.GetLogger(ctx, name, typeName) + logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)) logger.Debug("Creating middleware") logger.Debug("Setting up with expression: %s", expression) @@ -56,6 +56,5 @@ func (c *circuitBreaker) GetTracingInformation() (string, ext.SpanKindEnum) { } func (c *circuitBreaker) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - middlewares.GetLogger(req.Context(), c.name, typeName).Debug("Entering middleware") c.circuitBreaker.ServeHTTP(rw, req) } diff --git a/pkg/middlewares/compress/compress.go b/pkg/middlewares/compress/compress.go index 2e9be3b81..7269d2c39 100644 --- a/pkg/middlewares/compress/compress.go +++ b/pkg/middlewares/compress/compress.go @@ -7,10 +7,10 @@ import ( "strings" "github.com/NYTimes/gziphandler" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" - "github.com/sirupsen/logrus" ) const ( @@ -25,7 +25,7 @@ type compress struct { // New creates a new compress middleware. func New(ctx context.Context, next http.Handler, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") return &compress{ next: next, @@ -38,7 +38,8 @@ func (c *compress) ServeHTTP(rw http.ResponseWriter, req *http.Request) { if strings.HasPrefix(contentType, "application/grpc") { c.next.ServeHTTP(rw, req) } else { - gzipHandler(c.next, middlewares.GetLogger(req.Context(), c.name, typeName)).ServeHTTP(rw, req) + ctx := middlewares.GetLoggerCtx(req.Context(), c.name, typeName) + gzipHandler(ctx, c.next).ServeHTTP(rw, req) } } @@ -46,12 +47,12 @@ func (c *compress) GetTracingInformation() (string, ext.SpanKindEnum) { return c.name, tracing.SpanKindNoneEnum } -func gzipHandler(h http.Handler, logger logrus.FieldLogger) http.Handler { +func gzipHandler(ctx context.Context, h http.Handler) http.Handler { wrapper, err := gziphandler.GzipHandlerWithOpts( gziphandler.CompressionLevel(gzip.DefaultCompression), gziphandler.MinSize(gziphandler.DefaultMinSize)) if err != nil { - logger.Error(err) + log.FromContext(ctx).Error(err) } return wrapper(h) diff --git a/pkg/middlewares/customerrors/custom_errors.go b/pkg/middlewares/customerrors/custom_errors.go index c88c90c2f..72c70a631 100644 --- a/pkg/middlewares/customerrors/custom_errors.go +++ b/pkg/middlewares/customerrors/custom_errors.go @@ -12,6 +12,7 @@ import ( "strings" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/tracing" "github.com/containous/traefik/v2/pkg/types" @@ -43,7 +44,7 @@ type customErrors struct { // New creates a new custom error pages middleware. func New(ctx context.Context, next http.Handler, config dynamic.ErrorPage, serviceBuilder serviceBuilder, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") httpCodeRanges, err := types.NewHTTPCodeRanges(config.Status) if err != nil { @@ -69,7 +70,8 @@ func (c *customErrors) GetTracingInformation() (string, ext.SpanKindEnum) { } func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - logger := middlewares.GetLogger(req.Context(), c.name, typeName) + ctx := middlewares.GetLoggerCtx(req.Context(), c.name, typeName) + logger := log.FromContext(ctx) if c.backendHandler == nil { logger.Error("Error pages: no backend handler.") @@ -78,7 +80,7 @@ func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) { return } - recorder := newResponseRecorder(rw, middlewares.GetLogger(context.Background(), "test", typeName)) + recorder := newResponseRecorder(ctx, rw) c.next.ServeHTTP(recorder, req) // check the recorder code against the configured http status code ranges @@ -103,7 +105,7 @@ func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) { return } - recorderErrorPage := newResponseRecorder(rw, middlewares.GetLogger(context.Background(), "test", typeName)) + recorderErrorPage := newResponseRecorder(ctx, rw) utils.CopyHeaders(pageReq.Header, req.Header) c.backendHandler.ServeHTTP(recorderErrorPage, pageReq.WithContext(req.Context())) @@ -151,13 +153,13 @@ type responseRecorder interface { } // newResponseRecorder returns an initialized responseRecorder. -func newResponseRecorder(rw http.ResponseWriter, logger logrus.FieldLogger) responseRecorder { +func newResponseRecorder(ctx context.Context, rw http.ResponseWriter) responseRecorder { recorder := &responseRecorderWithoutCloseNotify{ HeaderMap: make(http.Header), Body: new(bytes.Buffer), Code: http.StatusOK, responseWriter: rw, - logger: logger, + logger: log.FromContext(ctx), } if _, ok := rw.(http.CloseNotifier); ok { return &responseRecorderWithCloseNotify{recorder} diff --git a/pkg/middlewares/customerrors/custom_errors_test.go b/pkg/middlewares/customerrors/custom_errors_test.go index 19aee2437..5dbb22f30 100644 --- a/pkg/middlewares/customerrors/custom_errors_test.go +++ b/pkg/middlewares/customerrors/custom_errors_test.go @@ -8,7 +8,6 @@ import ( "testing" "github.com/containous/traefik/v2/pkg/config/dynamic" - "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -151,7 +150,7 @@ func TestNewResponseRecorder(t *testing.T) { t.Run(test.desc, func(t *testing.T) { t.Parallel() - rec := newResponseRecorder(test.rw, middlewares.GetLogger(context.Background(), "test", typeName)) + rec := newResponseRecorder(context.Background(), test.rw) assert.IsType(t, rec, test.expected) }) } diff --git a/pkg/middlewares/headers/headers.go b/pkg/middlewares/headers/headers.go index 63a623e13..149b38219 100644 --- a/pkg/middlewares/headers/headers.go +++ b/pkg/middlewares/headers/headers.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" @@ -27,8 +28,9 @@ type headers struct { // New creates a Headers middleware. func New(ctx context.Context, next http.Handler, config dynamic.Headers, name string) (http.Handler, error) { // HeaderMiddleware -> SecureMiddleWare -> next - logger := middlewares.GetLogger(ctx, name, typeName) + logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)) logger.Debug("Creating middleware") + hasSecureHeaders := config.HasSecureHeadersDefined() hasCustomHeaders := config.HasCustomHeadersDefined() hasCorsHeaders := config.HasCorsHeadersDefined() diff --git a/pkg/middlewares/ipwhitelist/ip_whitelist.go b/pkg/middlewares/ipwhitelist/ip_whitelist.go index 20c9bd7bc..5e7468500 100644 --- a/pkg/middlewares/ipwhitelist/ip_whitelist.go +++ b/pkg/middlewares/ipwhitelist/ip_whitelist.go @@ -8,10 +8,10 @@ import ( "github.com/containous/traefik/v2/pkg/config/dynamic" "github.com/containous/traefik/v2/pkg/ip" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" - "github.com/sirupsen/logrus" ) const ( @@ -28,7 +28,7 @@ type ipWhiteLister struct { // New builds a new IPWhiteLister given a list of CIDR-Strings to whitelist func New(ctx context.Context, next http.Handler, config dynamic.IPWhiteList, name string) (http.Handler, error) { - logger := middlewares.GetLogger(ctx, name, typeName) + logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)) logger.Debug("Creating middleware") if len(config.SourceRange) == 0 { @@ -46,6 +46,7 @@ func New(ctx context.Context, next http.Handler, config dynamic.IPWhiteList, nam } logger.Debugf("Setting up IPWhiteLister with sourceRange: %s", config.SourceRange) + return &ipWhiteLister{ strategy: strategy, whiteLister: checker, @@ -59,14 +60,15 @@ func (wl *ipWhiteLister) GetTracingInformation() (string, ext.SpanKindEnum) { } func (wl *ipWhiteLister) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - logger := middlewares.GetLogger(req.Context(), wl.name, typeName) + ctx := middlewares.GetLoggerCtx(req.Context(), wl.name, typeName) + logger := log.FromContext(ctx) err := wl.whiteLister.IsAuthorized(wl.strategy.GetIP(req)) if err != nil { logMessage := fmt.Sprintf("rejecting request %+v: %v", req, err) logger.Debug(logMessage) tracing.SetErrorWithEvent(req, logMessage) - reject(logger, rw) + reject(ctx, rw) return } logger.Debugf("Accept %s: %+v", wl.strategy.GetIP(req), req) @@ -74,12 +76,12 @@ func (wl *ipWhiteLister) ServeHTTP(rw http.ResponseWriter, req *http.Request) { wl.next.ServeHTTP(rw, req) } -func reject(logger logrus.FieldLogger, rw http.ResponseWriter) { +func reject(ctx context.Context, rw http.ResponseWriter) { statusCode := http.StatusForbidden rw.WriteHeader(statusCode) _, err := rw.Write([]byte(http.StatusText(statusCode))) if err != nil { - logger.Error(err) + log.FromContext(ctx).Error(err) } } diff --git a/pkg/middlewares/metrics/metrics.go b/pkg/middlewares/metrics/metrics.go index 6f86095e7..b5f36640a 100644 --- a/pkg/middlewares/metrics/metrics.go +++ b/pkg/middlewares/metrics/metrics.go @@ -39,7 +39,7 @@ type metricsMiddleware struct { // NewEntryPointMiddleware creates a new metrics middleware for an Entrypoint. func NewEntryPointMiddleware(ctx context.Context, next http.Handler, registry metrics.Registry, entryPointName string) http.Handler { - middlewares.GetLogger(ctx, nameEntrypoint, typeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, nameEntrypoint, typeName)).Debug("Creating middleware") return &metricsMiddleware{ next: next, @@ -52,7 +52,7 @@ func NewEntryPointMiddleware(ctx context.Context, next http.Handler, registry me // NewServiceMiddleware creates a new metrics middleware for a Service. func NewServiceMiddleware(ctx context.Context, next http.Handler, registry metrics.Registry, serviceName string) http.Handler { - middlewares.GetLogger(ctx, nameService, typeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, nameService, typeName)).Debug("Creating middleware") return &metricsMiddleware{ next: next, diff --git a/pkg/middlewares/middleware.go b/pkg/middlewares/middleware.go index 2b76b2bc8..c340151cf 100644 --- a/pkg/middlewares/middleware.go +++ b/pkg/middlewares/middleware.go @@ -4,10 +4,9 @@ import ( "context" "github.com/containous/traefik/v2/pkg/log" - "github.com/sirupsen/logrus" ) -// GetLogger creates a logger configured with the middleware fields. -func GetLogger(ctx context.Context, middleware string, middlewareType string) logrus.FieldLogger { - return log.FromContext(ctx).WithField(log.MiddlewareName, middleware).WithField(log.MiddlewareType, middlewareType) +// GetLoggerCtx creates a logger context with the middleware fields. +func GetLoggerCtx(ctx context.Context, middleware string, middlewareType string) context.Context { + return log.With(ctx, log.Str(log.MiddlewareName, middleware), log.Str(log.MiddlewareType, middlewareType)) } diff --git a/pkg/middlewares/passtlsclientcert/pass_tls_client_cert.go b/pkg/middlewares/passtlsclientcert/pass_tls_client_cert.go index 64d6f2fea..a07bb9a73 100644 --- a/pkg/middlewares/passtlsclientcert/pass_tls_client_cert.go +++ b/pkg/middlewares/passtlsclientcert/pass_tls_client_cert.go @@ -16,7 +16,6 @@ import ( "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" - "github.com/sirupsen/logrus" ) const ( @@ -66,7 +65,7 @@ type passTLSClientCert struct { // New constructs a new PassTLSClientCert instance from supplied frontend header struct. func New(ctx context.Context, next http.Handler, config dynamic.PassTLSClientCert, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") return &passTLSClientCert{ next: next, @@ -104,11 +103,13 @@ func (p *passTLSClientCert) GetTracingInformation() (string, ext.SpanKindEnum) { } func (p *passTLSClientCert) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - logger := middlewares.GetLogger(req.Context(), p.name, typeName) - p.modifyRequestHeaders(logger, req) + ctx := middlewares.GetLoggerCtx(req.Context(), p.name, typeName) + + p.modifyRequestHeaders(ctx, req) p.next.ServeHTTP(rw, req) } -func getDNInfo(prefix string, options *DistinguishedNameOptions, cs *pkix.Name) string { + +func getDNInfo(ctx context.Context, prefix string, options *DistinguishedNameOptions, cs *pkix.Name) string { if options == nil { return "" } @@ -124,27 +125,27 @@ func getDNInfo(prefix string, options *DistinguishedNameOptions, cs *pkix.Name) } if options.CountryName { - writeParts(content, cs.Country, "C") + writeParts(ctx, content, cs.Country, "C") } if options.StateOrProvinceName { - writeParts(content, cs.Province, "ST") + writeParts(ctx, content, cs.Province, "ST") } if options.LocalityName { - writeParts(content, cs.Locality, "L") + writeParts(ctx, content, cs.Locality, "L") } if options.OrganizationName { - writeParts(content, cs.Organization, "O") + writeParts(ctx, content, cs.Organization, "O") } if options.SerialNumber { - writePart(content, cs.SerialNumber, "SN") + writePart(ctx, content, cs.SerialNumber, "SN") } if options.CommonName { - writePart(content, cs.CommonName, "CN") + writePart(ctx, content, cs.CommonName, "CN") } if content.Len() > 0 { @@ -154,24 +155,24 @@ func getDNInfo(prefix string, options *DistinguishedNameOptions, cs *pkix.Name) return "" } -func writeParts(content io.StringWriter, entries []string, prefix string) { +func writeParts(ctx context.Context, content io.StringWriter, entries []string, prefix string) { for _, entry := range entries { - writePart(content, entry, prefix) + writePart(ctx, content, entry, prefix) } } -func writePart(content io.StringWriter, entry string, prefix string) { +func writePart(ctx context.Context, content io.StringWriter, entry string, prefix string) { if len(entry) > 0 { _, err := content.WriteString(fmt.Sprintf("%s=%s,", prefix, entry)) if err != nil { - log.Error(err) + log.FromContext(ctx).Error(err) } } } // getXForwardedTLSClientCertInfo Build a string with the wanted client certificates information // like Subject="C=%s,ST=%s,L=%s,O=%s,CN=%s",NB=%d,NA=%d,SAN=%s; -func (p *passTLSClientCert) getXForwardedTLSClientCertInfo(certs []*x509.Certificate) string { +func (p *passTLSClientCert) getXForwardedTLSClientCertInfo(ctx context.Context, certs []*x509.Certificate) string { var headerValues []string for _, peerCert := range certs { @@ -181,12 +182,12 @@ func (p *passTLSClientCert) getXForwardedTLSClientCertInfo(certs []*x509.Certifi var na string if p.info != nil { - subject := getDNInfo("Subject", p.info.subject, &peerCert.Subject) + subject := getDNInfo(ctx, "Subject", p.info.subject, &peerCert.Subject) if len(subject) > 0 { values = append(values, subject) } - issuer := getDNInfo("Issuer", p.info.issuer, &peerCert.Issuer) + issuer := getDNInfo(ctx, "Issuer", p.info.issuer, &peerCert.Issuer) if len(issuer) > 0 { values = append(values, issuer) } @@ -217,10 +218,12 @@ func (p *passTLSClientCert) getXForwardedTLSClientCertInfo(certs []*x509.Certifi } // modifyRequestHeaders set the wanted headers with the certificates information. -func (p *passTLSClientCert) modifyRequestHeaders(logger logrus.FieldLogger, r *http.Request) { +func (p *passTLSClientCert) modifyRequestHeaders(ctx context.Context, r *http.Request) { + logger := log.FromContext(ctx) + if p.pem { if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 { - r.Header.Set(xForwardedTLSClientCert, getXForwardedTLSClientCert(logger, r.TLS.PeerCertificates)) + r.Header.Set(xForwardedTLSClientCert, getXForwardedTLSClientCert(ctx, r.TLS.PeerCertificates)) } else { logger.Warn("Tried to extract a certificate on a request without mutual TLS") } @@ -228,7 +231,7 @@ func (p *passTLSClientCert) modifyRequestHeaders(logger logrus.FieldLogger, r *h if p.info != nil { if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 { - headerContent := p.getXForwardedTLSClientCertInfo(r.TLS.PeerCertificates) + headerContent := p.getXForwardedTLSClientCertInfo(ctx, r.TLS.PeerCertificates) r.Header.Set(xForwardedTLSClientCertInfo, url.QueryEscape(headerContent)) } else { logger.Warn("Tried to extract a certificate on a request without mutual TLS") @@ -248,22 +251,22 @@ func sanitize(cert []byte) string { } // extractCertificate extract the certificate from the request. -func extractCertificate(logger logrus.FieldLogger, cert *x509.Certificate) string { +func extractCertificate(ctx context.Context, cert *x509.Certificate) string { b := pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw} certPEM := pem.EncodeToMemory(&b) if certPEM == nil { - logger.Error("Cannot extract the certificate content") + log.FromContext(ctx).Error("Cannot extract the certificate content") return "" } return sanitize(certPEM) } // getXForwardedTLSClientCert Build a string with the client certificates. -func getXForwardedTLSClientCert(logger logrus.FieldLogger, certs []*x509.Certificate) string { +func getXForwardedTLSClientCert(ctx context.Context, certs []*x509.Certificate) string { var headerValues []string for _, peerCert := range certs { - headerValues = append(headerValues, extractCertificate(logger, peerCert)) + headerValues = append(headerValues, extractCertificate(ctx, peerCert)) } return strings.Join(headerValues, ",") diff --git a/pkg/middlewares/pipelining/pipelining.go b/pkg/middlewares/pipelining/pipelining.go index e2cf2898a..a4e14110a 100644 --- a/pkg/middlewares/pipelining/pipelining.go +++ b/pkg/middlewares/pipelining/pipelining.go @@ -6,6 +6,7 @@ import ( "net" "net/http" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" ) @@ -20,7 +21,7 @@ type pipelining struct { // New returns a new pipelining instance func New(ctx context.Context, next http.Handler, name string) http.Handler { - middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") return &pipelining{ next: next, diff --git a/pkg/middlewares/ratelimiter/rate_limiter.go b/pkg/middlewares/ratelimiter/rate_limiter.go index 73682c200..4e51ec3c9 100644 --- a/pkg/middlewares/ratelimiter/rate_limiter.go +++ b/pkg/middlewares/ratelimiter/rate_limiter.go @@ -90,7 +90,8 @@ func (rl *rateLimiter) GetTracingInformation() (string, ext.SpanKindEnum) { } func (rl *rateLimiter) ServeHTTP(w http.ResponseWriter, r *http.Request) { - logger := middlewares.GetLogger(r.Context(), rl.name, typeName) + ctx := middlewares.GetLoggerCtx(r.Context(), rl.name, typeName) + logger := log.FromContext(ctx) source, amount, err := rl.sourceMatcher.Extract(r) if err != nil { @@ -127,7 +128,7 @@ func (rl *rateLimiter) ServeHTTP(w http.ResponseWriter, r *http.Request) { delay := res.Delay() if delay > rl.maxDelay { res.Cancel() - rl.serveDelayError(w, r, delay) + rl.serveDelayError(ctx, w, r, delay) return } @@ -135,12 +136,12 @@ func (rl *rateLimiter) ServeHTTP(w http.ResponseWriter, r *http.Request) { rl.next.ServeHTTP(w, r) } -func (rl *rateLimiter) serveDelayError(w http.ResponseWriter, r *http.Request, delay time.Duration) { +func (rl *rateLimiter) serveDelayError(ctx context.Context, w http.ResponseWriter, r *http.Request, delay time.Duration) { w.Header().Set("Retry-After", fmt.Sprintf("%.0f", delay.Seconds())) w.Header().Set("X-Retry-In", delay.String()) w.WriteHeader(http.StatusTooManyRequests) if _, err := w.Write([]byte(http.StatusText(http.StatusTooManyRequests))); err != nil { - middlewares.GetLogger(r.Context(), rl.name, typeName).Errorf("could not serve 429: %v", err) + log.FromContext(ctx).Errorf("could not serve 429: %v", err) } } diff --git a/pkg/middlewares/recovery/recovery.go b/pkg/middlewares/recovery/recovery.go index 054b2d402..563d52e66 100644 --- a/pkg/middlewares/recovery/recovery.go +++ b/pkg/middlewares/recovery/recovery.go @@ -4,8 +4,8 @@ import ( "context" "net/http" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" - "github.com/sirupsen/logrus" ) const ( @@ -19,7 +19,7 @@ type recovery struct { // New creates recovery middleware. func New(ctx context.Context, next http.Handler, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") return &recovery{ next: next, @@ -28,13 +28,13 @@ func New(ctx context.Context, next http.Handler, name string) (http.Handler, err } func (re *recovery) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - defer recoverFunc(middlewares.GetLogger(req.Context(), re.name, typeName), rw) + defer recoverFunc(middlewares.GetLoggerCtx(req.Context(), re.name, typeName), rw) re.next.ServeHTTP(rw, req) } -func recoverFunc(logger logrus.FieldLogger, rw http.ResponseWriter) { +func recoverFunc(ctx context.Context, rw http.ResponseWriter) { if err := recover(); err != nil { - logger.Errorf("Recovered from panic in http handler: %+v", err) + log.FromContext(ctx).Errorf("Recovered from panic in http handler: %+v", err) http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) } } diff --git a/pkg/middlewares/redirect/redirect.go b/pkg/middlewares/redirect/redirect.go index 541c4ab7c..0e87013c3 100644 --- a/pkg/middlewares/redirect/redirect.go +++ b/pkg/middlewares/redirect/redirect.go @@ -2,7 +2,6 @@ package redirect import ( "bytes" - "context" "html/template" "io" "net/http" @@ -25,7 +24,7 @@ type redirect struct { } // New creates a Redirect middleware. -func newRedirect(_ context.Context, next http.Handler, regex string, replacement string, permanent bool, name string) (http.Handler, error) { +func newRedirect(next http.Handler, regex string, replacement string, permanent bool, name string) (http.Handler, error) { re, err := regexp.Compile(regex) if err != nil { return nil, err diff --git a/pkg/middlewares/redirect/redirect_regex.go b/pkg/middlewares/redirect/redirect_regex.go index 0c8f6406e..7e366574a 100644 --- a/pkg/middlewares/redirect/redirect_regex.go +++ b/pkg/middlewares/redirect/redirect_regex.go @@ -5,6 +5,7 @@ import ( "net/http" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" ) @@ -14,9 +15,9 @@ const ( // NewRedirectRegex creates a redirect middleware. func NewRedirectRegex(ctx context.Context, next http.Handler, conf dynamic.RedirectRegex, name string) (http.Handler, error) { - logger := middlewares.GetLogger(ctx, name, typeRegexName) + logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeRegexName)) logger.Debug("Creating middleware") logger.Debugf("Setting up redirection from %s to %s", conf.Regex, conf.Replacement) - return newRedirect(ctx, next, conf.Regex, conf.Replacement, conf.Permanent, name) + return newRedirect(next, conf.Regex, conf.Replacement, conf.Permanent, name) } diff --git a/pkg/middlewares/redirect/redirect_scheme.go b/pkg/middlewares/redirect/redirect_scheme.go index 0ffd5d704..92523c70e 100644 --- a/pkg/middlewares/redirect/redirect_scheme.go +++ b/pkg/middlewares/redirect/redirect_scheme.go @@ -6,6 +6,7 @@ import ( "net/http" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" ) @@ -16,7 +17,7 @@ const ( // NewRedirectScheme creates a new RedirectScheme middleware. func NewRedirectScheme(ctx context.Context, next http.Handler, conf dynamic.RedirectScheme, name string) (http.Handler, error) { - logger := middlewares.GetLogger(ctx, name, typeSchemeName) + logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeSchemeName)) logger.Debug("Creating middleware") logger.Debugf("Setting up redirection to %s %s", conf.Scheme, conf.Port) @@ -29,5 +30,5 @@ func NewRedirectScheme(ctx context.Context, next http.Handler, conf dynamic.Redi port = ":" + conf.Port } - return newRedirect(ctx, next, schemeRedirectRegex, conf.Scheme+"://${2}"+port+"${4}", conf.Permanent, name) + return newRedirect(next, schemeRedirectRegex, conf.Scheme+"://${2}"+port+"${4}", conf.Permanent, name) } diff --git a/pkg/middlewares/replacepath/replace_path.go b/pkg/middlewares/replacepath/replace_path.go index a53cc9a54..bec16827d 100644 --- a/pkg/middlewares/replacepath/replace_path.go +++ b/pkg/middlewares/replacepath/replace_path.go @@ -5,6 +5,7 @@ import ( "net/http" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" @@ -25,7 +26,7 @@ type replacePath struct { // New creates a new replace path middleware. func New(ctx context.Context, next http.Handler, config dynamic.ReplacePath, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") return &replacePath{ next: next, @@ -42,5 +43,6 @@ func (r *replacePath) ServeHTTP(rw http.ResponseWriter, req *http.Request) { req.Header.Add(ReplacedPathHeader, req.URL.Path) req.URL.Path = r.path req.RequestURI = req.URL.RequestURI() + r.next.ServeHTTP(rw, req) } diff --git a/pkg/middlewares/replacepathregex/replace_path_regex.go b/pkg/middlewares/replacepathregex/replace_path_regex.go index 89d3b062a..c23820fbd 100644 --- a/pkg/middlewares/replacepathregex/replace_path_regex.go +++ b/pkg/middlewares/replacepathregex/replace_path_regex.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/middlewares/replacepath" "github.com/containous/traefik/v2/pkg/tracing" @@ -28,7 +29,7 @@ type replacePathRegex struct { // New creates a new replace path regex middleware. func New(ctx context.Context, next http.Handler, config dynamic.ReplacePathRegex, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") exp, err := regexp.Compile(strings.TrimSpace(config.Regex)) if err != nil { diff --git a/pkg/middlewares/retry/retry.go b/pkg/middlewares/retry/retry.go index 05fd158f1..937ef1b04 100644 --- a/pkg/middlewares/retry/retry.go +++ b/pkg/middlewares/retry/retry.go @@ -10,6 +10,7 @@ import ( "net/http/httptrace" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" @@ -43,8 +44,7 @@ type retry struct { // New returns a new retry middleware. func New(ctx context.Context, next http.Handler, config dynamic.Retry, listener Listener, name string) (http.Handler, error) { - logger := middlewares.GetLogger(ctx, name, typeName) - logger.Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") if config.Attempts <= 0 { return nil, fmt.Errorf("incorrect (or empty) value for attempt (%d)", config.Attempts) @@ -94,8 +94,10 @@ func (r *retry) ServeHTTP(rw http.ResponseWriter, req *http.Request) { } attempts++ - logger := middlewares.GetLogger(req.Context(), r.name, typeName) - logger.Debugf("New attempt %d for request: %v", attempts, req.URL) + + log.FromContext(middlewares.GetLoggerCtx(req.Context(), r.name, typeName)). + Debugf("New attempt %d for request: %v", attempts, req.URL) + r.listener.Retried(req, attempts) } } diff --git a/pkg/middlewares/stripprefix/strip_prefix.go b/pkg/middlewares/stripprefix/strip_prefix.go index 31bc5ae90..b8008689a 100644 --- a/pkg/middlewares/stripprefix/strip_prefix.go +++ b/pkg/middlewares/stripprefix/strip_prefix.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" @@ -26,7 +27,7 @@ type stripPrefix struct { // New creates a new strip prefix middleware. func New(ctx context.Context, next http.Handler, config dynamic.StripPrefix, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") return &stripPrefix{ prefixes: config.Prefixes, next: next, diff --git a/pkg/middlewares/stripprefixregex/strip_prefix_regex.go b/pkg/middlewares/stripprefixregex/strip_prefix_regex.go index 6cc82f178..4024ac4f0 100644 --- a/pkg/middlewares/stripprefixregex/strip_prefix_regex.go +++ b/pkg/middlewares/stripprefixregex/strip_prefix_regex.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/middlewares/stripprefix" "github.com/containous/traefik/v2/pkg/tracing" @@ -26,7 +27,7 @@ type stripPrefixRegex struct { // New builds a new StripPrefixRegex middleware. func New(ctx context.Context, next http.Handler, config dynamic.StripPrefixRegex, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") stripPrefix := stripPrefixRegex{ next: next, diff --git a/pkg/middlewares/tracing/entrypoint.go b/pkg/middlewares/tracing/entrypoint.go index f7eeb7dc9..195cc994f 100644 --- a/pkg/middlewares/tracing/entrypoint.go +++ b/pkg/middlewares/tracing/entrypoint.go @@ -5,6 +5,7 @@ import ( "net/http" "github.com/containous/alice" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go" @@ -17,7 +18,7 @@ const ( // NewEntryPoint creates a new middleware that the incoming request. func NewEntryPoint(ctx context.Context, t *tracing.Tracing, entryPointName string, next http.Handler) http.Handler { - middlewares.GetLogger(ctx, "tracing", entryPointTypeName).Debug("Creating middleware") + log.FromContext(middlewares.GetLoggerCtx(ctx, "tracing", entryPointTypeName)).Debug("Creating middleware") return &entryPointMiddleware{ entryPoint: entryPointName, diff --git a/pkg/middlewares/tracing/forwarder.go b/pkg/middlewares/tracing/forwarder.go index 25f8ba8bc..4c689a06a 100644 --- a/pkg/middlewares/tracing/forwarder.go +++ b/pkg/middlewares/tracing/forwarder.go @@ -4,6 +4,7 @@ import ( "context" "net/http" + "github.com/containous/traefik/v2/pkg/log" "github.com/containous/traefik/v2/pkg/middlewares" "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" @@ -21,7 +22,7 @@ type forwarderMiddleware struct { // NewForwarder creates a new forwarder middleware that traces the outgoing request. func NewForwarder(ctx context.Context, router, service string, next http.Handler) http.Handler { - middlewares.GetLogger(ctx, "tracing", forwarderTypeName). + log.FromContext(middlewares.GetLoggerCtx(ctx, "tracing", forwarderTypeName)). Debugf("Added outgoing tracing middleware %s", service) return &forwarderMiddleware{ diff --git a/pkg/provider/acme/provider.go b/pkg/provider/acme/provider.go index 2025eb5ff..ecf28a363 100644 --- a/pkg/provider/acme/provider.go +++ b/pkg/provider/acme/provider.go @@ -350,17 +350,19 @@ func (p *Provider) watchNewDomains(ctx context.Context) { if route.TLS == nil || route.TLS.CertResolver != p.ResolverName { continue } + ctxRouter := log.With(ctx, log.Str(log.RouterName, routerName), log.Str(log.Rule, route.Rule)) + logger := log.FromContext(ctxRouter) tlsStore := "default" if len(route.TLS.Domains) > 0 { for _, domain := range route.TLS.Domains { if domain.Main != dns01.UnFqdn(domain.Main) { - log.Warnf("FQDN detected, please remove the trailing dot: %s", domain.Main) + logger.Warnf("FQDN detected, please remove the trailing dot: %s", domain.Main) } for _, san := range domain.SANs { if san != dns01.UnFqdn(san) { - log.Warnf("FQDN detected, please remove the trailing dot: %s", san) + logger.Warnf("FQDN detected, please remove the trailing dot: %s", san) } } } @@ -378,7 +380,7 @@ func (p *Provider) watchNewDomains(ctx context.Context) { } else { domains, err := rules.ParseHostSNI(route.Rule) if err != nil { - log.FromContext(ctxRouter).Errorf("Error parsing domains in provider ACME: %v", err) + logger.Errorf("Error parsing domains in provider ACME: %v", err) continue } p.resolveDomains(ctxRouter, domains, tlsStore) diff --git a/pkg/provider/docker/config.go b/pkg/provider/docker/config.go index 86f097665..9c3c18bf0 100644 --- a/pkg/provider/docker/config.go +++ b/pkg/provider/docker/config.go @@ -85,8 +85,9 @@ func (p *Provider) buildTCPServiceConfiguration(ctx context.Context, container d } } - for _, service := range configuration.Services { - err := p.addServerTCP(ctx, container, service.LoadBalancer) + for name, service := range configuration.Services { + ctxSvc := log.With(ctx, log.Str(log.ServiceName, name)) + err := p.addServerTCP(ctxSvc, container, service.LoadBalancer) if err != nil { return err } @@ -107,8 +108,9 @@ func (p *Provider) buildServiceConfiguration(ctx context.Context, container dock } } - for _, service := range configuration.Services { - err := p.addServer(ctx, container, service.LoadBalancer) + for name, service := range configuration.Services { + ctxSvc := log.With(ctx, log.Str(log.ServiceName, name)) + err := p.addServer(ctxSvc, container, service.LoadBalancer) if err != nil { return err } diff --git a/pkg/provider/file/file.go b/pkg/provider/file/file.go index 2ab456373..667be1205 100644 --- a/pkg/provider/file/file.go +++ b/pkg/provider/file/file.go @@ -85,7 +85,7 @@ func (p *Provider) BuildConfiguration() (*dynamic.Configuration, error) { } if len(p.Filename) > 0 { - return p.loadFileConfig(p.Filename, true) + return p.loadFileConfig(ctx, p.Filename, true) } return nil, errors.New("error using file configuration provider, neither filename or directory defined") @@ -156,11 +156,11 @@ func sendConfigToChannel(configurationChan chan<- dynamic.Message, configuration } } -func (p *Provider) loadFileConfig(filename string, parseTemplate bool) (*dynamic.Configuration, error) { +func (p *Provider) loadFileConfig(ctx context.Context, filename string, parseTemplate bool) (*dynamic.Configuration, error) { var err error var configuration *dynamic.Configuration if parseTemplate { - configuration, err = p.CreateConfiguration(filename, template.FuncMap{}, false) + configuration, err = p.CreateConfiguration(ctx, filename, template.FuncMap{}, false) } else { configuration, err = p.DecodeConfiguration(filename) } @@ -169,25 +169,25 @@ func (p *Provider) loadFileConfig(filename string, parseTemplate bool) (*dynamic } if configuration.TLS != nil { - configuration.TLS.Certificates = flattenCertificates(configuration.TLS) + configuration.TLS.Certificates = flattenCertificates(ctx, configuration.TLS) } return configuration, nil } -func flattenCertificates(tlsConfig *dynamic.TLSConfiguration) []*tls.CertAndStores { +func flattenCertificates(ctx context.Context, tlsConfig *dynamic.TLSConfiguration) []*tls.CertAndStores { var certs []*tls.CertAndStores for _, cert := range tlsConfig.Certificates { content, err := cert.Certificate.CertFile.Read() if err != nil { - log.Error(err) + log.FromContext(ctx).Error(err) continue } cert.Certificate.CertFile = tls.FileOrContent(string(content)) content, err = cert.Certificate.KeyFile.Read() if err != nil { - log.Error(err) + log.FromContext(ctx).Error(err) continue } cert.Certificate.KeyFile = tls.FileOrContent(string(content)) @@ -243,7 +243,7 @@ func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory st } var c *dynamic.Configuration - c, err = p.loadFileConfig(filepath.Join(directory, item.Name()), true) + c, err = p.loadFileConfig(ctx, filepath.Join(directory, item.Name()), true) if err != nil { return configuration, err } @@ -331,7 +331,7 @@ func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory st } // CreateConfiguration creates a provider configuration from content using templating. -func (p *Provider) CreateConfiguration(filename string, funcMap template.FuncMap, templateObjects interface{}) (*dynamic.Configuration, error) { +func (p *Provider) CreateConfiguration(ctx context.Context, filename string, funcMap template.FuncMap, templateObjects interface{}) (*dynamic.Configuration, error) { tmplContent, err := readFile(filename) if err != nil { return nil, fmt.Errorf("error reading configuration file: %s - %s", filename, err) @@ -359,7 +359,7 @@ func (p *Provider) CreateConfiguration(filename string, funcMap template.FuncMap var renderedTemplate = buffer.String() if p.DebugLogGeneratedTemplate { - logger := log.WithoutContext().WithField(log.ProviderName, providerName) + logger := log.FromContext(ctx) logger.Debugf("Template content: %s", tmplContent) logger.Debugf("Rendering results: %s", renderedTemplate) } diff --git a/pkg/provider/file/file_test.go b/pkg/provider/file/file_test.go index fab3f6d1d..f4892823f 100644 --- a/pkg/provider/file/file_test.go +++ b/pkg/provider/file/file_test.go @@ -46,7 +46,7 @@ func TestTLSContent(t *testing.T) { require.NoError(t, err) provider := &Provider{} - configuration, err := provider.loadFileConfig(fileConfig.Name(), true) + configuration, err := provider.loadFileConfig(context.Background(), fileConfig.Name(), true) require.NoError(t, err) require.Equal(t, "CONTENT", configuration.TLS.Certificates[0].Certificate.CertFile.String()) diff --git a/pkg/safe/routine.go b/pkg/safe/routine.go index 83f33b872..f02cfda9b 100644 --- a/pkg/safe/routine.go +++ b/pkg/safe/routine.go @@ -155,8 +155,9 @@ func GoWithRecover(goroutine func(), customRecover func(err interface{})) { } func defaultRecoverGoroutine(err interface{}) { - log.Errorf("Error in Go routine: %s", err) - log.Errorf("Stack: %s", debug.Stack()) + logger := log.WithoutContext() + logger.Errorf("Error in Go routine: %s", err) + logger.Errorf("Stack: %s", debug.Stack()) } // OperationWithRecover wrap a backoff operation in a Recover diff --git a/pkg/server/cookie/cookie.go b/pkg/server/cookie/cookie.go index 632763a8f..5ac3339be 100644 --- a/pkg/server/cookie/cookie.go +++ b/pkg/server/cookie/cookie.go @@ -27,7 +27,7 @@ func GenerateName(backendName string) string { _, err := hash.Write(data) if err != nil { // Impossible case - log.Errorf("Fail to create cookie name: %v", err) + log.WithoutContext().Errorf("Fail to create cookie name: %v", err) } return fmt.Sprintf("_%x", hash.Sum(nil))[:cookieNameLength] diff --git a/pkg/server/router/tcp/router_test.go b/pkg/server/router/tcp/router_test.go index 86fb882c6..d55aa98b0 100644 --- a/pkg/server/router/tcp/router_test.go +++ b/pkg/server/router/tcp/router_test.go @@ -203,6 +203,7 @@ func TestRuntimeConfiguration(t *testing.T) { serviceManager := tcp.NewManager(conf) tlsManager := tls.NewManager() tlsManager.UpdateConfigs( + context.Background(), map[string]tls.Store{}, map[string]tls.Options{ "default": { diff --git a/pkg/server/server.go b/pkg/server/server.go index 7a67e46f9..234d66e0d 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -270,7 +270,8 @@ func (s *Server) listenProviders(stop chan bool) { if configMsg.Configuration != nil { s.preLoadConfiguration(configMsg) } else { - log.Debugf("Received nil configuration from provider %q, skipping.", configMsg.ProviderName) + log.WithoutContext().WithField(log.ProviderName, configMsg.ProviderName). + Debug("Received nil configuration from provider, skipping.") } } } @@ -285,18 +286,20 @@ func (s *Server) AddListener(listener func(dynamic.Configuration)) { } func (s *Server) startProvider() { + logger := log.WithoutContext() + jsonConf, err := json.Marshal(s.provider) if err != nil { - log.WithoutContext().Debugf("Unable to marshal provider configuration %T: %v", s.provider, err) + logger.Debugf("Unable to marshal provider configuration %T: %v", s.provider, err) } - log.WithoutContext().Infof("Starting provider %T %s", s.provider, jsonConf) + logger.Infof("Starting provider %T %s", s.provider, jsonConf) currentProvider := s.provider safe.Go(func() { err := currentProvider.Provide(s.configurationChan, s.routinesPool) if err != nil { - log.WithoutContext().Errorf("Error starting provider %T: %s", s.provider, err) + logger.Errorf("Error starting provider %T: %s", s.provider, err) } }) } diff --git a/pkg/server/server_configuration.go b/pkg/server/server_configuration.go index c4b703504..edeb0ede4 100644 --- a/pkg/server/server_configuration.go +++ b/pkg/server/server_configuration.go @@ -63,7 +63,7 @@ func (s *Server) loadConfiguration(configMsg dynamic.Message) { // loadConfigurationTCP returns a new gorilla.mux Route from the specified global configuration and the dynamic // provider configurations. func (s *Server) loadConfigurationTCP(configurations dynamic.Configurations) map[string]*tcpCore.Router { - ctx := context.TODO() + ctx := context.Background() var entryPoints []string for entryPointName := range s.entryPointsTCP { @@ -72,7 +72,7 @@ func (s *Server) loadConfigurationTCP(configurations dynamic.Configurations) map conf := mergeConfiguration(configurations) - s.tlsManager.UpdateConfigs(conf.TLS.Stores, conf.TLS.Options, conf.TLS.Certificates) + s.tlsManager.UpdateConfigs(ctx, conf.TLS.Stores, conf.TLS.Options, conf.TLS.Certificates) rtConf := runtime.NewConfig(conf) handlersNonTLS, handlersTLS := s.createHTTPHandlers(ctx, rtConf, entryPoints) diff --git a/pkg/server/server_entrypoint_tcp.go b/pkg/server/server_entrypoint_tcp.go index cad56b3ab..59db9ba85 100644 --- a/pkg/server/server_entrypoint_tcp.go +++ b/pkg/server/server_entrypoint_tcp.go @@ -72,14 +72,14 @@ func NewTCPEntryPoint(ctx context.Context, configuration *static.EntryPoint) (*T router := &tcp.Router{} - httpServer, err := createHTTPServer(listener, configuration, true) + httpServer, err := createHTTPServer(ctx, listener, configuration, true) if err != nil { return nil, fmt.Errorf("error preparing httpServer: %v", err) } router.HTTPForwarder(httpServer.Forwarder) - httpsServer, err := createHTTPServer(listener, configuration, false) + httpsServer, err := createHTTPServer(ctx, listener, configuration, false) if err != nil { return nil, fmt.Errorf("error preparing httpsServer: %v", err) } @@ -128,13 +128,13 @@ func writeCloser(conn net.Conn) (tcp.WriteCloser, error) { } func (e *TCPEntryPoint) startTCP(ctx context.Context) { - - log.FromContext(ctx).Debugf("Start TCP Server") + logger := log.FromContext(ctx) + logger.Debugf("Start TCP Server") for { conn, err := e.listener.Accept() if err != nil { - log.Error(err) + logger.Error(err) return } @@ -372,7 +372,7 @@ type httpServer struct { Switcher *middlewares.HTTPHandlerSwitcher } -func createHTTPServer(ln net.Listener, configuration *static.EntryPoint, withH2c bool) (*httpServer, error) { +func createHTTPServer(ctx context.Context, ln net.Listener, configuration *static.EntryPoint, withH2c bool) (*httpServer, error) { httpSwitcher := middlewares.NewHandlerSwitcher(buildDefaultHTTPRouter()) var handler http.Handler @@ -398,7 +398,7 @@ func createHTTPServer(ln net.Listener, configuration *static.EntryPoint, withH2c go func() { err := serverHTTP.Serve(listener) if err != nil { - log.Errorf("Error while starting server: %v", err) + log.FromContext(ctx).Errorf("Error while starting server: %v", err) } }() return &httpServer{ diff --git a/pkg/server/service/service.go b/pkg/server/service/service.go index 1181b2584..bb030889a 100644 --- a/pkg/server/service/service.go +++ b/pkg/server/service/service.go @@ -232,7 +232,7 @@ func (m *Manager) LaunchHealthCheck() { } // FIXME metrics and context - healthcheck.GetHealthCheck().SetBackendsConfiguration(context.TODO(), backendConfigs) + healthcheck.GetHealthCheck().SetBackendsConfiguration(context.Background(), backendConfigs) } func buildHealthCheckOptions(ctx context.Context, lb healthcheck.BalancerHandler, backend string, hc *dynamic.HealthCheck) *healthcheck.Options { diff --git a/pkg/tcp/rr_load_balancer.go b/pkg/tcp/rr_load_balancer.go index 92be94f54..eb5773ae2 100644 --- a/pkg/tcp/rr_load_balancer.go +++ b/pkg/tcp/rr_load_balancer.go @@ -39,7 +39,7 @@ func (r *RRLoadBalancer) next() Handler { if r.current >= len(r.servers) { r.current = 0 - log.Debugf("Load balancer: going back to the first available server") + log.WithoutContext().Debugf("Load balancer: going back to the first available server") } handler := r.servers[r.current] diff --git a/pkg/tls/tlsmanager.go b/pkg/tls/tlsmanager.go index 27fdbb1eb..ebdeb9e22 100644 --- a/pkg/tls/tlsmanager.go +++ b/pkg/tls/tlsmanager.go @@ -1,6 +1,7 @@ package tls import ( + "context" "crypto/tls" "crypto/x509" "errors" @@ -30,7 +31,7 @@ func NewManager() *Manager { } // UpdateConfigs updates the TLS* configuration options -func (m *Manager) UpdateConfigs(stores map[string]Store, configs map[string]Options, certs []*CertAndStores) { +func (m *Manager) UpdateConfigs(ctx context.Context, stores map[string]Store, configs map[string]Options, certs []*CertAndStores) { m.lock.Lock() defer m.lock.Unlock() @@ -40,9 +41,10 @@ func (m *Manager) UpdateConfigs(stores map[string]Store, configs map[string]Opti m.stores = make(map[string]*CertificateStore) for storeName, storeConfig := range m.storesConfig { - store, err := buildCertificateStore(storeConfig) + ctxStore := log.With(ctx, log.Str(log.TLSStoreName, storeName)) + store, err := buildCertificateStore(ctxStore, storeConfig) if err != nil { - log.Errorf("Error while creating certificate store %s: %v", storeName, err) + log.FromContext(ctxStore).Errorf("Error while creating certificate store: %v", err) continue } m.stores[storeName] = store @@ -52,14 +54,15 @@ func (m *Manager) UpdateConfigs(stores map[string]Store, configs map[string]Opti for _, conf := range certs { if len(conf.Stores) == 0 { if log.GetLevel() >= logrus.DebugLevel { - log.Debugf("No store is defined to add the certificate %s, it will be added to the default store.", + log.FromContext(ctx).Debugf("No store is defined to add the certificate %s, it will be added to the default store.", conf.Certificate.GetTruncatedCertificateName()) } conf.Stores = []string{"default"} } for _, store := range conf.Stores { + ctxStore := log.With(ctx, log.Str(log.TLSStoreName, store)) if err := conf.Certificate.AppendCertificate(storesCertificates, store); err != nil { - log.Errorf("Unable to append certificate %s to store %s: %v", conf.Certificate.GetTruncatedCertificateName(), store, err) + log.FromContext(ctxStore).Errorf("Unable to append certificate %s to store: %v", conf.Certificate.GetTruncatedCertificateName(), err) } } } @@ -125,7 +128,7 @@ func (m *Manager) Get(storeName string, configName string) (*tls.Config, error) func (m *Manager) getStore(storeName string) *CertificateStore { _, ok := m.stores[storeName] if !ok { - m.stores[storeName], _ = buildCertificateStore(Store{}) + m.stores[storeName], _ = buildCertificateStore(context.Background(), Store{}) } return m.stores[storeName] } @@ -138,7 +141,7 @@ func (m *Manager) GetStore(storeName string) *CertificateStore { return m.getStore(storeName) } -func buildCertificateStore(tlsStore Store) (*CertificateStore, error) { +func buildCertificateStore(ctx context.Context, tlsStore Store) (*CertificateStore, error) { certificateStore := NewCertificateStore() certificateStore.DynamicCerts.Set(make(map[string]*tls.Certificate)) @@ -149,7 +152,7 @@ func buildCertificateStore(tlsStore Store) (*CertificateStore, error) { } certificateStore.DefaultCertificate = cert } else { - log.Debug("No default certificate, generating one") + log.FromContext(ctx).Debug("No default certificate, generating one") cert, err := generate.DefaultCertificate() if err != nil { return certificateStore, err diff --git a/pkg/tls/tlsmanager_test.go b/pkg/tls/tlsmanager_test.go index 9fcc4935b..06b364ea1 100644 --- a/pkg/tls/tlsmanager_test.go +++ b/pkg/tls/tlsmanager_test.go @@ -1,6 +1,7 @@ package tls import ( + "context" "crypto/tls" "crypto/x509" "encoding/pem" @@ -57,7 +58,7 @@ func TestTLSInStore(t *testing.T) { }} tlsManager := NewManager() - tlsManager.UpdateConfigs(nil, nil, dynamicConfigs) + tlsManager.UpdateConfigs(context.Background(), nil, nil, dynamicConfigs) certs := tlsManager.GetStore("default").DynamicCerts.Get().(map[string]*tls.Certificate) if len(certs) == 0 { @@ -74,14 +75,15 @@ func TestTLSInvalidStore(t *testing.T) { }} tlsManager := NewManager() - tlsManager.UpdateConfigs(map[string]Store{ - "default": { - DefaultCertificate: &Certificate{ - CertFile: "/wrong", - KeyFile: "/wrong", + tlsManager.UpdateConfigs(context.Background(), + map[string]Store{ + "default": { + DefaultCertificate: &Certificate{ + CertFile: "/wrong", + KeyFile: "/wrong", + }, }, - }, - }, nil, dynamicConfigs) + }, nil, dynamicConfigs) certs := tlsManager.GetStore("default").DynamicCerts.Get().(map[string]*tls.Certificate) if len(certs) == 0 { @@ -131,7 +133,7 @@ func TestManager_Get(t *testing.T) { } tlsManager := NewManager() - tlsManager.UpdateConfigs(nil, tlsConfigs, dynamicConfigs) + tlsManager.UpdateConfigs(context.Background(), nil, tlsConfigs, dynamicConfigs) for _, test := range testCases { test := test @@ -270,7 +272,7 @@ func TestClientAuth(t *testing.T) { } tlsManager := NewManager() - tlsManager.UpdateConfigs(nil, tlsConfigs, nil) + tlsManager.UpdateConfigs(context.Background(), nil, tlsConfigs, nil) for _, test := range testCases { test := test diff --git a/pkg/version/version.go b/pkg/version/version.go index c208f650e..7b5975bf1 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -43,7 +43,7 @@ func (v Handler) Append(router *mux.Router) { } if err := templatesRenderer.JSON(response, http.StatusOK, v); err != nil { - log.Error(err) + log.WithoutContext().Error(err) } }) } @@ -53,34 +53,39 @@ func CheckNewVersion() { if Version == "dev" { return } + + logger := log.WithoutContext() + client := github.NewClient(nil) + updateURL, err := url.Parse("https://update.traefik.io/") if err != nil { - log.Warnf("Error checking new version: %s", err) + logger.Warnf("Error checking new version: %s", err) return } client.BaseURL = updateURL + releases, resp, err := client.Repositories.ListReleases(context.Background(), "containous", "traefik", nil) if err != nil { - log.Warnf("Error checking new version: %s", err) + logger.Warnf("Error checking new version: %s", err) return } if resp.StatusCode != http.StatusOK { - log.Warnf("Error checking new version: status=%s", resp.Status) + logger.Warnf("Error checking new version: status=%s", resp.Status) return } currentVersion, err := goversion.NewVersion(Version) if err != nil { - log.Warnf("Error checking new version: %s", err) + logger.Warnf("Error checking new version: %s", err) return } for _, release := range releases { releaseVersion, err := goversion.NewVersion(*release.TagName) if err != nil { - log.Warnf("Error checking new version: %s", err) + logger.Warnf("Error checking new version: %s", err) return } @@ -89,7 +94,7 @@ func CheckNewVersion() { } if releaseVersion.GreaterThan(currentVersion) { - log.Warnf("A new release has been found: %s. Please consider updating.", releaseVersion.String()) + logger.Warnf("A new release has been found: %s. Please consider updating.", releaseVersion.String()) return } }