New logger for the Traefik logs
This commit is contained in:
parent
27c02b5a56
commit
56f7515ecd
297 changed files with 2337 additions and 1934 deletions
|
@ -7,10 +7,10 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/config/runtime"
|
||||
"github.com/traefik/traefik/v2/pkg/config/static"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/version"
|
||||
)
|
||||
|
||||
|
@ -138,7 +138,7 @@ func (h Handler) getRuntimeConfiguration(rw http.ResponseWriter, request *http.R
|
|||
|
||||
err := json.NewEncoder(rw).Encode(result)
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,8 +8,8 @@ import (
|
|||
"strconv"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/static"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
)
|
||||
|
||||
type entryPointRepresentation struct {
|
||||
|
@ -43,7 +43,7 @@ func (h Handler) getEntryPoints(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex])
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -66,7 +66,7 @@ func (h Handler) getEntryPoint(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err := json.NewEncoder(rw).Encode(result)
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,8 +9,8 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/runtime"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/tls"
|
||||
)
|
||||
|
||||
|
@ -93,7 +93,7 @@ func (h Handler) getRouters(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex])
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -113,7 +113,7 @@ func (h Handler) getRouter(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err := json.NewEncoder(rw).Encode(result)
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -145,7 +145,7 @@ func (h Handler) getServices(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex])
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -165,7 +165,7 @@ func (h Handler) getService(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err := json.NewEncoder(rw).Encode(result)
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -197,7 +197,7 @@ func (h Handler) getMiddlewares(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex])
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -217,7 +217,7 @@ func (h Handler) getMiddleware(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err := json.NewEncoder(rw).Encode(result)
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,9 +5,9 @@ import (
|
|||
"net/http"
|
||||
"reflect"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/runtime"
|
||||
"github.com/traefik/traefik/v2/pkg/config/static"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
)
|
||||
|
||||
type schemeOverview struct {
|
||||
|
@ -62,7 +62,7 @@ func (h Handler) getOverview(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err := json.NewEncoder(rw).Encode(result)
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,8 +9,8 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/runtime"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
)
|
||||
|
||||
type tcpRouterRepresentation struct {
|
||||
|
@ -86,7 +86,7 @@ func (h Handler) getTCPRouters(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex])
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -106,7 +106,7 @@ func (h Handler) getTCPRouter(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err := json.NewEncoder(rw).Encode(result)
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -138,7 +138,7 @@ func (h Handler) getTCPServices(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex])
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -158,7 +158,7 @@ func (h Handler) getTCPService(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err := json.NewEncoder(rw).Encode(result)
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -190,7 +190,7 @@ func (h Handler) getTCPMiddlewares(rw http.ResponseWriter, request *http.Request
|
|||
|
||||
err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex])
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -210,7 +210,7 @@ func (h Handler) getTCPMiddleware(rw http.ResponseWriter, request *http.Request)
|
|||
|
||||
err := json.NewEncoder(rw).Encode(result)
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,8 +9,8 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/runtime"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
)
|
||||
|
||||
type udpRouterRepresentation struct {
|
||||
|
@ -70,7 +70,7 @@ func (h Handler) getUDPRouters(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex])
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -90,7 +90,7 @@ func (h Handler) getUDPRouter(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err := json.NewEncoder(rw).Encode(result)
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -122,7 +122,7 @@ func (h Handler) getUDPServices(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex])
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -142,7 +142,7 @@ func (h Handler) getUDPService(rw http.ResponseWriter, request *http.Request) {
|
|||
|
||||
err := json.NewEncoder(rw).Encode(result)
|
||||
if err != nil {
|
||||
log.FromContext(request.Context()).Error(err)
|
||||
log.Ctx(request.Context()).Error().Err(err).Send()
|
||||
writeError(rw, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,9 +5,9 @@ import (
|
|||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/paerser/cli"
|
||||
"github.com/traefik/paerser/env"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
)
|
||||
|
||||
// EnvLoader loads a configuration from all the environment variables prefixed with "TRAEFIK_".
|
||||
|
@ -21,11 +21,11 @@ func (e *EnvLoader) Load(_ []string, cmd *cli.Command) (bool, error) {
|
|||
}
|
||||
|
||||
if err := env.Decode(vars, env.DefaultNamePrefix, cmd.Configuration); err != nil {
|
||||
log.WithoutContext().Debug("environment variables", strings.Join(vars, ", "))
|
||||
return false, fmt.Errorf("failed to decode configuration from environment variables: %w ", err)
|
||||
log.Debug().Msgf("environment variables: %s", strings.Join(vars, ", "))
|
||||
return false, fmt.Errorf("failed to decode configuration from environment variables: %w", err)
|
||||
}
|
||||
|
||||
log.WithoutContext().Println("Configuration loaded from environment variables.")
|
||||
log.Print("Configuration loaded from environment variables")
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
|
|
@ -4,10 +4,10 @@ import (
|
|||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/paerser/cli"
|
||||
"github.com/traefik/paerser/file"
|
||||
"github.com/traefik/paerser/flag"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
)
|
||||
|
||||
// FileLoader loads a configuration from a file.
|
||||
|
@ -52,11 +52,10 @@ func (f *FileLoader) Load(args []string, cmd *cli.Command) (bool, error) {
|
|||
return false, nil
|
||||
}
|
||||
|
||||
logger := log.WithoutContext()
|
||||
logger.Printf("Configuration loaded from file: %s", configFile)
|
||||
log.Printf("Configuration loaded from file: %s", configFile)
|
||||
|
||||
content, _ := os.ReadFile(configFile)
|
||||
logger.Debug(string(content))
|
||||
log.Debug().Str("configFile", configFile).Bytes("content", content).Send()
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
|
|
@ -3,9 +3,9 @@ package cli
|
|||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/paerser/cli"
|
||||
"github.com/traefik/paerser/flag"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
)
|
||||
|
||||
// FlagLoader loads configuration from flags.
|
||||
|
@ -21,7 +21,7 @@ func (*FlagLoader) Load(args []string, cmd *cli.Command) (bool, error) {
|
|||
return false, fmt.Errorf("failed to decode configuration from flags: %w", err)
|
||||
}
|
||||
|
||||
log.WithoutContext().Println("Configuration loaded from flags.")
|
||||
log.Print("Configuration loaded from flags")
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
|
|
@ -10,8 +10,8 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/mitchellh/hashstructure"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/static"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/redactor"
|
||||
"github.com/traefik/traefik/v2/pkg/version"
|
||||
)
|
||||
|
@ -49,7 +49,7 @@ func createBody(staticConfiguration *static.Configuration) (*bytes.Buffer, error
|
|||
return nil, err
|
||||
}
|
||||
|
||||
log.WithoutContext().Infof("Anonymous stats sent to %s: %s", collectorURL, anonConfig)
|
||||
log.Debug().Msgf("Anonymous stats sent to %s: %s", collectorURL, anonConfig)
|
||||
|
||||
hashConf, err := hashstructure.Hash(staticConfiguration, nil)
|
||||
if err != nil {
|
||||
|
|
|
@ -4,8 +4,9 @@ import (
|
|||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
)
|
||||
|
||||
// Status of the router/service.
|
||||
|
@ -116,8 +117,6 @@ func (c *Configuration) PopulateUsedBy() {
|
|||
return
|
||||
}
|
||||
|
||||
logger := log.WithoutContext()
|
||||
|
||||
for routerName, routerInfo := range c.Routers {
|
||||
// lazily initialize Status in case caller forgot to do it
|
||||
if routerInfo.Status == "" {
|
||||
|
@ -126,7 +125,7 @@ func (c *Configuration) PopulateUsedBy() {
|
|||
|
||||
providerName := getProviderName(routerName)
|
||||
if providerName == "" {
|
||||
logger.WithField(log.RouterName, routerName).Error("router name is not fully qualified")
|
||||
log.Error().Str(logs.RouterName, routerName).Msg("Router name is not fully qualified")
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -171,7 +170,7 @@ func (c *Configuration) PopulateUsedBy() {
|
|||
|
||||
providerName := getProviderName(routerName)
|
||||
if providerName == "" {
|
||||
logger.WithField(log.RouterName, routerName).Error("tcp router name is not fully qualified")
|
||||
log.Error().Str(logs.RouterName, routerName).Msg("TCP router name is not fully qualified")
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -208,7 +207,7 @@ func (c *Configuration) PopulateUsedBy() {
|
|||
|
||||
providerName := getProviderName(routerName)
|
||||
if providerName == "" {
|
||||
logger.WithField(log.RouterName, routerName).Error("udp router name is not fully qualified")
|
||||
log.Error().Str(logs.RouterName, routerName).Msg("UDP router name is not fully qualified")
|
||||
continue
|
||||
}
|
||||
|
||||
|
|
|
@ -6,8 +6,9 @@ import (
|
|||
"sort"
|
||||
"sync"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
)
|
||||
|
||||
// GetRoutersByEntryPoints returns all the http routers by entry points name and routers name.
|
||||
|
@ -19,14 +20,14 @@ func (c *Configuration) GetRoutersByEntryPoints(ctx context.Context, entryPoints
|
|||
continue
|
||||
}
|
||||
|
||||
logger := log.FromContext(log.With(ctx, log.Str(log.RouterName, rtName)))
|
||||
logger := log.Ctx(ctx).With().Str(logs.RouterName, rtName).Logger()
|
||||
|
||||
entryPointsCount := 0
|
||||
for _, entryPointName := range rt.EntryPoints {
|
||||
if !contains(entryPoints, entryPointName) {
|
||||
rt.AddError(fmt.Errorf("entryPoint %q doesn't exist", entryPointName), false)
|
||||
logger.WithField(log.EntryPointName, entryPointName).
|
||||
Errorf("entryPoint %q doesn't exist", entryPointName)
|
||||
logger.Error().Str(logs.EntryPointName, entryPointName).
|
||||
Msg("EntryPoint doesn't exist")
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -42,7 +43,7 @@ func (c *Configuration) GetRoutersByEntryPoints(ctx context.Context, entryPoints
|
|||
|
||||
if entryPointsCount == 0 {
|
||||
rt.AddError(fmt.Errorf("no valid entryPoint for this router"), true)
|
||||
logger.Error("no valid entryPoint for this router")
|
||||
logger.Error().Msg("No valid entryPoint for this router")
|
||||
}
|
||||
|
||||
rt.Using = unique(rt.Using)
|
||||
|
|
|
@ -4,8 +4,9 @@ import (
|
|||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
)
|
||||
|
||||
// GetTCPRoutersByEntryPoints returns all the tcp routers by entry points name and routers name.
|
||||
|
@ -13,14 +14,14 @@ func (c *Configuration) GetTCPRoutersByEntryPoints(ctx context.Context, entryPoi
|
|||
entryPointsRouters := make(map[string]map[string]*TCPRouterInfo)
|
||||
|
||||
for rtName, rt := range c.TCPRouters {
|
||||
logger := log.FromContext(log.With(ctx, log.Str(log.RouterName, rtName)))
|
||||
logger := log.Ctx(ctx).With().Str(logs.RouterName, rtName).Logger()
|
||||
|
||||
entryPointsCount := 0
|
||||
for _, entryPointName := range rt.EntryPoints {
|
||||
if !contains(entryPoints, entryPointName) {
|
||||
rt.AddError(fmt.Errorf("entryPoint %q doesn't exist", entryPointName), false)
|
||||
logger.WithField(log.EntryPointName, entryPointName).
|
||||
Errorf("entryPoint %q doesn't exist", entryPointName)
|
||||
logger.Error().Str(logs.EntryPointName, entryPointName).
|
||||
Msg("EntryPoint doesn't exist")
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -36,7 +37,7 @@ func (c *Configuration) GetTCPRoutersByEntryPoints(ctx context.Context, entryPoi
|
|||
|
||||
if entryPointsCount == 0 {
|
||||
rt.AddError(fmt.Errorf("no valid entryPoint for this router"), true)
|
||||
logger.Error("no valid entryPoint for this router")
|
||||
logger.Error().Msg("No valid entryPoint for this router")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -4,8 +4,9 @@ import (
|
|||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
)
|
||||
|
||||
// GetUDPRoutersByEntryPoints returns all the UDP routers by entry points name and routers name.
|
||||
|
@ -13,11 +14,11 @@ func (c *Configuration) GetUDPRoutersByEntryPoints(ctx context.Context, entryPoi
|
|||
entryPointsRouters := make(map[string]map[string]*UDPRouterInfo)
|
||||
|
||||
for rtName, rt := range c.UDPRouters {
|
||||
logger := log.FromContext(log.With(ctx, log.Str(log.RouterName, rtName)))
|
||||
logger := log.Ctx(ctx).With().Str(logs.RouterName, rtName).Logger()
|
||||
|
||||
eps := rt.EntryPoints
|
||||
if len(eps) == 0 {
|
||||
logger.Debugf("No entryPoint defined for this router, using the default one(s) instead: %+v", entryPoints)
|
||||
logger.Debug().Msgf("No entryPoint defined for this router, using the default one(s) instead: %+v", entryPoints)
|
||||
eps = entryPoints
|
||||
}
|
||||
|
||||
|
@ -25,8 +26,8 @@ func (c *Configuration) GetUDPRoutersByEntryPoints(ctx context.Context, entryPoi
|
|||
for _, entryPointName := range eps {
|
||||
if !contains(entryPoints, entryPointName) {
|
||||
rt.AddError(fmt.Errorf("entryPoint %q doesn't exist", entryPointName), false)
|
||||
logger.WithField(log.EntryPointName, entryPointName).
|
||||
Errorf("entryPoint %q doesn't exist", entryPointName)
|
||||
logger.Error().Str(logs.EntryPointName, entryPointName).
|
||||
Msg("EntryPoint doesn't exist")
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -42,7 +43,7 @@ func (c *Configuration) GetUDPRoutersByEntryPoints(ctx context.Context, entryPoi
|
|||
|
||||
if entryPointsCount == 0 {
|
||||
rt.AddError(fmt.Errorf("no valid entryPoint for this router"), true)
|
||||
logger.Error("no valid entryPoint for this router")
|
||||
logger.Error().Msg("No valid entryPoint for this router")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -3,7 +3,8 @@ package static
|
|||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/provider/hub"
|
||||
)
|
||||
|
||||
|
@ -18,7 +19,9 @@ func (c *Configuration) initHubProvider() error {
|
|||
ep.SetDefaults()
|
||||
ep.Address = ":9901"
|
||||
c.EntryPoints[hub.TunnelEntrypoint] = &ep
|
||||
log.WithoutContext().Infof("The entryPoint %q is created on port 9901 to allow exposition of services.", hub.TunnelEntrypoint)
|
||||
|
||||
log.Info().Str(logs.EntryPointName, hub.TunnelEntrypoint).
|
||||
Msg("The entryPoint is created on port 9901 to allow exposition of services.")
|
||||
}
|
||||
|
||||
if c.Hub.TLS == nil {
|
||||
|
@ -34,7 +37,7 @@ func (c *Configuration) initHubProvider() error {
|
|||
}
|
||||
|
||||
if c.Hub.TLS.Insecure {
|
||||
log.WithoutContext().Warn("Hub is in `insecure` mode. Do not run in production with this setup.")
|
||||
log.Warn().Msg("Hub is in `insecure` mode. Do not run in production with this setup.")
|
||||
}
|
||||
|
||||
if _, ok := c.EntryPoints[hub.APIEntrypoint]; !ok {
|
||||
|
@ -42,7 +45,9 @@ func (c *Configuration) initHubProvider() error {
|
|||
ep.SetDefaults()
|
||||
ep.Address = ":9900"
|
||||
c.EntryPoints[hub.APIEntrypoint] = &ep
|
||||
log.WithoutContext().Infof("The entryPoint %q is created on port 9900 to allow Traefik to communicate with the Hub Agent for Traefik.", hub.APIEntrypoint)
|
||||
|
||||
log.Info().Str(logs.EntryPointName, hub.APIEntrypoint).
|
||||
Msg("The entryPoint is created on port 9900 to allow Traefik to communicate with the Hub Agent for Traefik.")
|
||||
}
|
||||
|
||||
c.EntryPoints[hub.APIEntrypoint].HTTP.TLS = &TLSConfig{
|
||||
|
|
|
@ -2,14 +2,14 @@ package static
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
stdlog "log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
legolog "github.com/go-acme/lego/v4/log"
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
ptypes "github.com/traefik/paerser/types"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/ping"
|
||||
acmeprovider "github.com/traefik/traefik/v2/pkg/provider/acme"
|
||||
"github.com/traefik/traefik/v2/pkg/provider/consulcatalog"
|
||||
|
@ -242,9 +242,9 @@ func (c *Configuration) SetEffectiveConfiguration() {
|
|||
if c.Hub != nil {
|
||||
if err := c.initHubProvider(); err != nil {
|
||||
c.Hub = nil
|
||||
log.WithoutContext().Errorf("Unable to activate the Hub provider: %v", err)
|
||||
log.Error().Err(err).Msg("Unable to activate the Hub provider")
|
||||
} else {
|
||||
log.WithoutContext().Debugf("Experimental Hub provider has been activated.")
|
||||
log.Debug().Msg("Experimental Hub provider has been activated")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -278,14 +278,15 @@ func (c *Configuration) SetEffectiveConfiguration() {
|
|||
for epName, ep := range c.EntryPoints {
|
||||
if ep.HTTP3 != nil {
|
||||
ep.HTTP3 = nil
|
||||
log.WithoutContext().Debugf("Disabling HTTP3 configuration for entryPoint %q: HTTP3 is disabled in the experimental configuration section", epName)
|
||||
log.Debug().Str(logs.EntryPointName, epName).
|
||||
Msgf("Disabling HTTP3 configuration for entryPoint %q: HTTP3 is disabled in the experimental configuration section", epName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Configure Gateway API provider
|
||||
if c.Providers.KubernetesGateway != nil {
|
||||
log.WithoutContext().Debugf("Experimental Kubernetes Gateway provider has been activated")
|
||||
log.Debug().Msg("Experimental Kubernetes Gateway provider has been activated")
|
||||
entryPoints := make(map[string]gateway.Entrypoint)
|
||||
for epName, entryPoint := range c.EntryPoints {
|
||||
entryPoints[epName] = gateway.Entrypoint{Address: entryPoint.GetAddress(), HasHTTPTLSConf: entryPoint.HTTP.TLS != nil}
|
||||
|
@ -319,7 +320,8 @@ func (c *Configuration) initACMEProvider() {
|
|||
}
|
||||
}
|
||||
|
||||
legolog.Logger = stdlog.New(log.WithoutContext().WriterLevel(logrus.DebugLevel), "legolog: ", 0)
|
||||
logger := logs.NoLevel(log.Logger, zerolog.DebugLevel).With().Str("lib", "lego").Logger()
|
||||
legolog.Logger = logs.NewLogrusWrapper(logger)
|
||||
}
|
||||
|
||||
// ValidateConfiguration validate that configuration is coherent.
|
||||
|
@ -366,15 +368,13 @@ func getSafeACMECAServer(caServerSrc string) string {
|
|||
|
||||
if strings.HasPrefix(caServerSrc, "https://acme-v01.api.letsencrypt.org") {
|
||||
caServer := strings.Replace(caServerSrc, "v01", "v02", 1)
|
||||
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)
|
||||
log.Warn().Msgf("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.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)
|
||||
log.Warn().Msgf("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
|
||||
}
|
||||
|
||||
|
|
|
@ -11,9 +11,9 @@ import (
|
|||
"time"
|
||||
|
||||
gokitmetrics "github.com/go-kit/kit/metrics"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/config/runtime"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
@ -55,22 +55,22 @@ type ServiceHealthChecker struct {
|
|||
}
|
||||
|
||||
func NewServiceHealthChecker(ctx context.Context, metrics metricsHealthCheck, config *dynamic.ServerHealthCheck, service StatusSetter, info *runtime.ServiceInfo, transport http.RoundTripper, targets map[string]*url.URL) *ServiceHealthChecker {
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
interval := time.Duration(config.Interval)
|
||||
if interval <= 0 {
|
||||
logger.Error("Health check interval smaller than zero")
|
||||
logger.Error().Msg("Health check interval smaller than zero")
|
||||
interval = time.Duration(dynamic.DefaultHealthCheckInterval)
|
||||
}
|
||||
|
||||
timeout := time.Duration(config.Timeout)
|
||||
if timeout <= 0 {
|
||||
logger.Error("Health check timeout smaller than zero")
|
||||
logger.Error().Msg("Health check timeout smaller than zero")
|
||||
timeout = time.Duration(dynamic.DefaultHealthCheckTimeout)
|
||||
}
|
||||
|
||||
if timeout >= interval {
|
||||
logger.Warnf("Health check timeout should be lower than the health check interval. Interval set to timeout + 1 second (%s).", interval)
|
||||
logger.Warn().Msgf("Health check timeout should be lower than the health check interval. Interval set to timeout + 1 second (%s).", interval)
|
||||
interval = timeout + time.Second
|
||||
}
|
||||
|
||||
|
@ -122,10 +122,10 @@ func (shc *ServiceHealthChecker) Launch(ctx context.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
log.FromContext(ctx).
|
||||
WithField("targetURL", target.String()).
|
||||
WithError(err).
|
||||
Warn("Health check failed.")
|
||||
log.Ctx(ctx).Warn().
|
||||
Str("targetURL", target.String()).
|
||||
Err(err).
|
||||
Msg("Health check failed.")
|
||||
|
||||
up = false
|
||||
serverUpMetricValue = float64(0)
|
||||
|
|
|
@ -1,133 +0,0 @@
|
|||
package log
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"io"
|
||||
"runtime"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Debug logs a message at level Debug on the standard logger.
|
||||
// Deprecated: use log.FromContext(ctx).Debug(...) instead.
|
||||
func Debug(args ...interface{}) {
|
||||
mainLogger.Debug(args...)
|
||||
}
|
||||
|
||||
// Debugf logs a message at level Debug on the standard logger.
|
||||
// Deprecated: use log.FromContext(ctx).Debugf(...) instead.
|
||||
func Debugf(format string, args ...interface{}) {
|
||||
mainLogger.Debugf(format, args...)
|
||||
}
|
||||
|
||||
// Info logs a message at level Info on the standard logger.
|
||||
// Deprecated: use log.FromContext(ctx).Info(...) instead.
|
||||
func Info(args ...interface{}) {
|
||||
mainLogger.Info(args...)
|
||||
}
|
||||
|
||||
// Infof logs a message at level Info on the standard logger.
|
||||
// Deprecated: use log.FromContext(ctx).Infof(...) instead.
|
||||
func Infof(format string, args ...interface{}) {
|
||||
mainLogger.Infof(format, args...)
|
||||
}
|
||||
|
||||
// Warn logs a message at level Warn on the standard logger.
|
||||
// Deprecated: use log.FromContext(ctx).Warn(...) instead.
|
||||
func Warn(args ...interface{}) {
|
||||
mainLogger.Warn(args...)
|
||||
}
|
||||
|
||||
// Warnf logs a message at level Warn on the standard logger.
|
||||
// Deprecated: use log.FromContext(ctx).Warnf(...) instead.
|
||||
func Warnf(format string, args ...interface{}) {
|
||||
mainLogger.Warnf(format, args...)
|
||||
}
|
||||
|
||||
// Error logs a message at level Error on the standard logger.
|
||||
// Deprecated: use log.FromContext(ctx).Error(...) instead.
|
||||
func Error(args ...interface{}) {
|
||||
mainLogger.Error(args...)
|
||||
}
|
||||
|
||||
// Errorf logs a message at level Error on the standard logger.
|
||||
// Deprecated: use log.FromContext(ctx).Errorf(...) instead.
|
||||
func Errorf(format string, args ...interface{}) {
|
||||
mainLogger.Errorf(format, args...)
|
||||
}
|
||||
|
||||
// Panic logs a message at level Panic on the standard logger.
|
||||
// Deprecated: use log.FromContext(ctx).Panic(...) instead.
|
||||
func Panic(args ...interface{}) {
|
||||
mainLogger.Panic(args...)
|
||||
}
|
||||
|
||||
// Fatal logs a message at level Fatal on the standard logger.
|
||||
// Deprecated: use log.FromContext(ctx).Fatal(...) instead.
|
||||
func Fatal(args ...interface{}) {
|
||||
mainLogger.Fatal(args...)
|
||||
}
|
||||
|
||||
// Fatalf logs a message at level Fatal on the standard logger.
|
||||
// Deprecated: use log.FromContext(ctx).Fatalf(...) instead.
|
||||
func Fatalf(format string, args ...interface{}) {
|
||||
mainLogger.Fatalf(format, args...)
|
||||
}
|
||||
|
||||
// AddHook adds a hook to the standard logger hooks.
|
||||
func AddHook(hook logrus.Hook) {
|
||||
logrus.AddHook(hook)
|
||||
}
|
||||
|
||||
// CustomWriterLevel logs writer for a specific level. (with a custom scanner buffer size.)
|
||||
// adapted from github.com/Sirupsen/logrus/writer.go.
|
||||
func CustomWriterLevel(level logrus.Level, maxScanTokenSize int) *io.PipeWriter {
|
||||
reader, writer := io.Pipe()
|
||||
|
||||
var printFunc func(args ...interface{})
|
||||
|
||||
switch level {
|
||||
case logrus.DebugLevel:
|
||||
printFunc = Debug
|
||||
case logrus.InfoLevel:
|
||||
printFunc = Info
|
||||
case logrus.WarnLevel:
|
||||
printFunc = Warn
|
||||
case logrus.ErrorLevel:
|
||||
printFunc = Error
|
||||
case logrus.FatalLevel:
|
||||
printFunc = Fatal
|
||||
case logrus.PanicLevel:
|
||||
printFunc = Panic
|
||||
default:
|
||||
printFunc = mainLogger.Print
|
||||
}
|
||||
|
||||
go writerScanner(reader, maxScanTokenSize, printFunc)
|
||||
runtime.SetFinalizer(writer, writerFinalizer)
|
||||
|
||||
return writer
|
||||
}
|
||||
|
||||
// extract from github.com/Sirupsen/logrus/writer.go
|
||||
// Hack the buffer size.
|
||||
func writerScanner(reader io.ReadCloser, scanTokenSize int, printFunc func(args ...interface{})) {
|
||||
scanner := bufio.NewScanner(reader)
|
||||
|
||||
if scanTokenSize > bufio.MaxScanTokenSize {
|
||||
buf := make([]byte, bufio.MaxScanTokenSize)
|
||||
scanner.Buffer(buf, scanTokenSize)
|
||||
}
|
||||
|
||||
for scanner.Scan() {
|
||||
printFunc(scanner.Text())
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
Errorf("Error while reading from Writer: %s", err)
|
||||
}
|
||||
reader.Close()
|
||||
}
|
||||
|
||||
func writerFinalizer(writer *io.PipeWriter) {
|
||||
writer.Close()
|
||||
}
|
144
pkg/log/log.go
144
pkg/log/log.go
|
@ -1,144 +0,0 @@
|
|||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type contextKey int
|
||||
|
||||
const (
|
||||
loggerKey contextKey = iota
|
||||
)
|
||||
|
||||
// Logger the Traefik logger.
|
||||
type Logger interface {
|
||||
logrus.FieldLogger
|
||||
WriterLevel(logrus.Level) *io.PipeWriter
|
||||
}
|
||||
|
||||
var (
|
||||
mainLogger Logger
|
||||
logFilePath string
|
||||
logFile *os.File
|
||||
)
|
||||
|
||||
func init() {
|
||||
mainLogger = logrus.StandardLogger()
|
||||
logrus.SetOutput(os.Stdout)
|
||||
}
|
||||
|
||||
// SetLogger sets the logger.
|
||||
func SetLogger(l Logger) {
|
||||
mainLogger = l
|
||||
}
|
||||
|
||||
// SetOutput sets the standard logger output.
|
||||
func SetOutput(out io.Writer) {
|
||||
logrus.SetOutput(out)
|
||||
}
|
||||
|
||||
// SetFormatter sets the standard logger formatter.
|
||||
func SetFormatter(formatter logrus.Formatter) {
|
||||
logrus.SetFormatter(formatter)
|
||||
}
|
||||
|
||||
// SetLevel sets the standard logger level.
|
||||
func SetLevel(level logrus.Level) {
|
||||
logrus.SetLevel(level)
|
||||
}
|
||||
|
||||
// GetLevel returns the standard logger level.
|
||||
func GetLevel() logrus.Level {
|
||||
return logrus.GetLevel()
|
||||
}
|
||||
|
||||
// Str adds a string field.
|
||||
func Str(key, value string) func(logrus.Fields) {
|
||||
return func(fields logrus.Fields) {
|
||||
fields[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
// With Adds fields.
|
||||
func With(ctx context.Context, opts ...func(logrus.Fields)) context.Context {
|
||||
logger := FromContext(ctx)
|
||||
|
||||
fields := make(logrus.Fields)
|
||||
for _, opt := range opts {
|
||||
opt(fields)
|
||||
}
|
||||
logger = logger.WithFields(fields)
|
||||
|
||||
return context.WithValue(ctx, loggerKey, logger)
|
||||
}
|
||||
|
||||
// FromContext Gets the logger from context.
|
||||
func FromContext(ctx context.Context) Logger {
|
||||
if ctx == nil {
|
||||
panic("nil context")
|
||||
}
|
||||
|
||||
logger, ok := ctx.Value(loggerKey).(Logger)
|
||||
if !ok {
|
||||
logger = mainLogger
|
||||
}
|
||||
|
||||
return logger
|
||||
}
|
||||
|
||||
// WithoutContext Gets the main logger.
|
||||
func WithoutContext() Logger {
|
||||
return mainLogger
|
||||
}
|
||||
|
||||
// OpenFile opens the log file using the specified path.
|
||||
func OpenFile(path string) error {
|
||||
logFilePath = path
|
||||
|
||||
var err error
|
||||
logFile, err = os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o666)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
SetOutput(logFile)
|
||||
return nil
|
||||
}
|
||||
|
||||
// CloseFile closes the log and sets the Output to stdout.
|
||||
func CloseFile() error {
|
||||
logrus.SetOutput(os.Stdout)
|
||||
|
||||
if logFile != nil {
|
||||
return logFile.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RotateFile closes and reopens the log file to allow for rotation by an external source.
|
||||
// If the log isn't backed by a file then it does nothing.
|
||||
func RotateFile() error {
|
||||
logger := FromContext(context.Background())
|
||||
|
||||
if logFile == nil && logFilePath == "" {
|
||||
logger.Debug("Traefik log is not writing to a file, ignoring rotate request")
|
||||
return nil
|
||||
}
|
||||
|
||||
if logFile != nil {
|
||||
defer func(f *os.File) {
|
||||
_ = f.Close()
|
||||
}(logFile)
|
||||
}
|
||||
|
||||
if err := OpenFile(logFilePath); err != nil {
|
||||
return fmt.Errorf("error opening log file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
|
@ -1,57 +0,0 @@
|
|||
package log
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestLog(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
fields map[string]string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
desc: "Log with one field",
|
||||
fields: map[string]string{
|
||||
"foo": "bar",
|
||||
},
|
||||
expected: ` level=error msg="message test" foo=bar$`,
|
||||
},
|
||||
{
|
||||
desc: "Log with two fields",
|
||||
fields: map[string]string{
|
||||
"foo": "bar",
|
||||
"oof": "rab",
|
||||
},
|
||||
expected: ` level=error msg="message test" foo=bar oof=rab$`,
|
||||
},
|
||||
{
|
||||
desc: "Log without field",
|
||||
fields: map[string]string{},
|
||||
expected: ` level=error msg="message test"$`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
var buffer bytes.Buffer
|
||||
SetOutput(&buffer)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
for key, value := range test.fields {
|
||||
ctx = With(ctx, Str(key, value))
|
||||
}
|
||||
|
||||
FromContext(ctx).Error("message test")
|
||||
|
||||
assert.Regexp(t, test.expected, strings.TrimSpace(buffer.String()))
|
||||
})
|
||||
}
|
||||
}
|
16
pkg/logs/aws.go
Normal file
16
pkg/logs/aws.go
Normal file
|
@ -0,0 +1,16 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func NewAWSWrapper(logger zerolog.Logger) aws.LoggerFunc {
|
||||
if logger.GetLevel() > zerolog.DebugLevel {
|
||||
return func(args ...interface{}) {}
|
||||
}
|
||||
|
||||
return func(args ...interface{}) {
|
||||
logger.Debug().CallerSkipFrame(2).MsgFunc(msgFunc(args...))
|
||||
}
|
||||
}
|
17
pkg/logs/aws_test.go
Normal file
17
pkg/logs/aws_test.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func TestNewAWSWrapper(t *testing.T) {
|
||||
out := zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}
|
||||
|
||||
logger := NewAWSWrapper(zerolog.New(out).With().Caller().Logger())
|
||||
|
||||
logger.Log("foo")
|
||||
}
|
15
pkg/logs/datadog.go
Normal file
15
pkg/logs/datadog.go
Normal file
|
@ -0,0 +1,15 @@
|
|||
package logs
|
||||
|
||||
import "github.com/rs/zerolog"
|
||||
|
||||
type DatadogLogger struct {
|
||||
logger zerolog.Logger
|
||||
}
|
||||
|
||||
func NewDatadogLogger(logger zerolog.Logger) *DatadogLogger {
|
||||
return &DatadogLogger{logger: logger}
|
||||
}
|
||||
|
||||
func (d DatadogLogger) Log(msg string) {
|
||||
d.logger.Debug().CallerSkipFrame(1).Msg(msg)
|
||||
}
|
17
pkg/logs/datadog_test.go
Normal file
17
pkg/logs/datadog_test.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func TestNewDatadogLogger(t *testing.T) {
|
||||
out := zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}
|
||||
|
||||
logger := NewDatadogLogger(zerolog.New(out).With().Caller().Logger())
|
||||
|
||||
logger.Log("foo")
|
||||
}
|
19
pkg/logs/elastic.go
Normal file
19
pkg/logs/elastic.go
Normal file
|
@ -0,0 +1,19 @@
|
|||
package logs
|
||||
|
||||
import "github.com/rs/zerolog"
|
||||
|
||||
type ElasticLogger struct {
|
||||
logger zerolog.Logger
|
||||
}
|
||||
|
||||
func NewElasticLogger(logger zerolog.Logger) *ElasticLogger {
|
||||
return &ElasticLogger{logger: logger}
|
||||
}
|
||||
|
||||
func (l ElasticLogger) Debugf(format string, args ...interface{}) {
|
||||
l.logger.Debug().CallerSkipFrame(1).Msgf(format, args...)
|
||||
}
|
||||
|
||||
func (l ElasticLogger) Errorf(format string, args ...interface{}) {
|
||||
l.logger.Error().CallerSkipFrame(1).Msgf(format, args...)
|
||||
}
|
17
pkg/logs/elastic_test.go
Normal file
17
pkg/logs/elastic_test.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func TestNewElasticLogger(t *testing.T) {
|
||||
out := zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}
|
||||
|
||||
logger := NewElasticLogger(zerolog.New(out).With().Caller().Logger())
|
||||
|
||||
logger.Errorf("foo")
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package log
|
||||
package logs
|
||||
|
||||
// Log entry names.
|
||||
const (
|
||||
|
@ -12,6 +12,7 @@ const (
|
|||
MetricsProviderName = "metricsProviderName"
|
||||
TracingProviderName = "tracingProviderName"
|
||||
ServerName = "serverName"
|
||||
ServerIndex = "serverIndex"
|
||||
TLSStoreName = "tlsStoreName"
|
||||
ServersTransportName = "serversTransport"
|
||||
)
|
17
pkg/logs/gokit.go
Normal file
17
pkg/logs/gokit.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
kitlog "github.com/go-kit/kit/log"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func NewGoKitWrapper(logger zerolog.Logger) kitlog.LoggerFunc {
|
||||
if logger.GetLevel() > zerolog.DebugLevel {
|
||||
return func(args ...interface{}) error { return nil }
|
||||
}
|
||||
|
||||
return func(args ...interface{}) error {
|
||||
logger.Debug().CallerSkipFrame(2).MsgFunc(msgFunc(args...))
|
||||
return nil
|
||||
}
|
||||
}
|
17
pkg/logs/gokit_test.go
Normal file
17
pkg/logs/gokit_test.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func TestNewGoKitWrapper(t *testing.T) {
|
||||
out := zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}
|
||||
|
||||
logger := NewGoKitWrapper(zerolog.New(out).With().Caller().Logger())
|
||||
|
||||
_ = logger.Log("foo")
|
||||
}
|
28
pkg/logs/haystack.go
Normal file
28
pkg/logs/haystack.go
Normal file
|
@ -0,0 +1,28 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
type HaystackLogger struct {
|
||||
logger zerolog.Logger
|
||||
}
|
||||
|
||||
func NewHaystackLogger(logger zerolog.Logger) *HaystackLogger {
|
||||
return &HaystackLogger{logger: logger}
|
||||
}
|
||||
|
||||
// Error prints the error message.
|
||||
func (l HaystackLogger) Error(format string, v ...interface{}) {
|
||||
l.logger.Error().CallerSkipFrame(1).Msgf(format, v...)
|
||||
}
|
||||
|
||||
// Info prints the info message.
|
||||
func (l HaystackLogger) Info(format string, v ...interface{}) {
|
||||
l.logger.Info().CallerSkipFrame(1).Msgf(format, v...)
|
||||
}
|
||||
|
||||
// Debug prints the info message.
|
||||
func (l HaystackLogger) Debug(format string, v ...interface{}) {
|
||||
l.logger.Debug().CallerSkipFrame(1).Msgf(format, v...)
|
||||
}
|
17
pkg/logs/haystack_test.go
Normal file
17
pkg/logs/haystack_test.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func TestNewHaystackLogger(t *testing.T) {
|
||||
out := zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}
|
||||
|
||||
logger := NewHaystackLogger(zerolog.New(out).With().Caller().Logger())
|
||||
|
||||
logger.Info("foo")
|
||||
}
|
29
pkg/logs/instana.go
Normal file
29
pkg/logs/instana.go
Normal file
|
@ -0,0 +1,29 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
type InstanaLogger struct {
|
||||
logger zerolog.Logger
|
||||
}
|
||||
|
||||
func NewInstanaLogger(logger zerolog.Logger) *InstanaLogger {
|
||||
return &InstanaLogger{logger: logger}
|
||||
}
|
||||
|
||||
func (l InstanaLogger) Debug(args ...interface{}) {
|
||||
l.logger.Debug().CallerSkipFrame(1).MsgFunc(msgFunc(args...))
|
||||
}
|
||||
|
||||
func (l InstanaLogger) Info(args ...interface{}) {
|
||||
l.logger.Info().CallerSkipFrame(1).MsgFunc(msgFunc(args...))
|
||||
}
|
||||
|
||||
func (l InstanaLogger) Warn(args ...interface{}) {
|
||||
l.logger.Warn().CallerSkipFrame(1).MsgFunc(msgFunc(args...))
|
||||
}
|
||||
|
||||
func (l InstanaLogger) Error(args ...interface{}) {
|
||||
l.logger.Error().CallerSkipFrame(1).MsgFunc(msgFunc(args...))
|
||||
}
|
17
pkg/logs/instana_test.go
Normal file
17
pkg/logs/instana_test.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func TestNewInstanaLogger(t *testing.T) {
|
||||
out := zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}
|
||||
|
||||
logger := NewInstanaLogger(zerolog.New(out).With().Caller().Logger())
|
||||
|
||||
logger.Info("foo")
|
||||
}
|
23
pkg/logs/jaeger.go
Normal file
23
pkg/logs/jaeger.go
Normal file
|
@ -0,0 +1,23 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
// JaegerLogger is an implementation of the Logger interface that delegates to traefik log.
|
||||
type JaegerLogger struct {
|
||||
logger zerolog.Logger
|
||||
}
|
||||
|
||||
func NewJaegerLogger(logger zerolog.Logger) *JaegerLogger {
|
||||
return &JaegerLogger{logger: logger}
|
||||
}
|
||||
|
||||
func (l *JaegerLogger) Error(msg string) {
|
||||
l.logger.Error().CallerSkipFrame(1).Msg(msg)
|
||||
}
|
||||
|
||||
// Infof logs a message at debug priority.
|
||||
func (l *JaegerLogger) Infof(msg string, args ...interface{}) {
|
||||
l.logger.Debug().CallerSkipFrame(1).Msgf(msg, args...)
|
||||
}
|
17
pkg/logs/jaeger_test.go
Normal file
17
pkg/logs/jaeger_test.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func TestNewJaegerLogger(t *testing.T) {
|
||||
out := zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}
|
||||
|
||||
logger := NewJaegerLogger(zerolog.New(out).With().Caller().Logger())
|
||||
|
||||
logger.Infof("foo")
|
||||
}
|
35
pkg/logs/log.go
Normal file
35
pkg/logs/log.go
Normal file
|
@ -0,0 +1,35 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func NoLevel(logger zerolog.Logger, level zerolog.Level) zerolog.Logger {
|
||||
return logger.Hook(NewNoLevelHook(logger.GetLevel(), level))
|
||||
}
|
||||
|
||||
type NoLevelHook struct {
|
||||
minLevel zerolog.Level
|
||||
level zerolog.Level
|
||||
}
|
||||
|
||||
func NewNoLevelHook(minLevel zerolog.Level, level zerolog.Level) *NoLevelHook {
|
||||
return &NoLevelHook{minLevel: minLevel, level: level}
|
||||
}
|
||||
|
||||
func (n NoLevelHook) Run(e *zerolog.Event, level zerolog.Level, _ string) {
|
||||
if n.minLevel > n.level {
|
||||
e.Discard()
|
||||
return
|
||||
}
|
||||
|
||||
if level == zerolog.NoLevel {
|
||||
e.Str("level", n.level.String())
|
||||
}
|
||||
}
|
||||
|
||||
func msgFunc(i ...any) func() string {
|
||||
return func() string { return fmt.Sprint(i...) }
|
||||
}
|
17
pkg/logs/log_test.go
Normal file
17
pkg/logs/log_test.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func TestNoLevel(t *testing.T) {
|
||||
out := zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}
|
||||
|
||||
logger := NoLevel(zerolog.New(out).With().Caller().Logger(), zerolog.DebugLevel)
|
||||
|
||||
logger.Info().Msg("foo")
|
||||
}
|
49
pkg/logs/logrus.go
Normal file
49
pkg/logs/logrus.go
Normal file
|
@ -0,0 +1,49 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
type LogrusStdWrapper struct {
|
||||
logger zerolog.Logger
|
||||
}
|
||||
|
||||
func NewLogrusWrapper(logger zerolog.Logger) *LogrusStdWrapper {
|
||||
return &LogrusStdWrapper{logger: logger}
|
||||
}
|
||||
|
||||
func (l LogrusStdWrapper) Print(args ...interface{}) {
|
||||
l.logger.Debug().CallerSkipFrame(1).MsgFunc(msgFunc(args...))
|
||||
}
|
||||
|
||||
func (l LogrusStdWrapper) Printf(s string, args ...interface{}) {
|
||||
l.logger.Debug().CallerSkipFrame(1).Msgf(s, args...)
|
||||
}
|
||||
|
||||
func (l LogrusStdWrapper) Println(args ...interface{}) {
|
||||
l.logger.Debug().CallerSkipFrame(1).MsgFunc(msgFunc(args...))
|
||||
}
|
||||
|
||||
func (l LogrusStdWrapper) Fatal(args ...interface{}) {
|
||||
l.logger.Fatal().CallerSkipFrame(1).MsgFunc(msgFunc(args...))
|
||||
}
|
||||
|
||||
func (l LogrusStdWrapper) Fatalf(s string, args ...interface{}) {
|
||||
l.logger.Fatal().CallerSkipFrame(1).Msgf(s, args...)
|
||||
}
|
||||
|
||||
func (l LogrusStdWrapper) Fatalln(args ...interface{}) {
|
||||
l.logger.Fatal().CallerSkipFrame(1).MsgFunc(msgFunc(args...))
|
||||
}
|
||||
|
||||
func (l LogrusStdWrapper) Panic(args ...interface{}) {
|
||||
l.logger.Panic().CallerSkipFrame(1).MsgFunc(msgFunc(args...))
|
||||
}
|
||||
|
||||
func (l LogrusStdWrapper) Panicf(s string, args ...interface{}) {
|
||||
l.logger.Panic().CallerSkipFrame(1).Msgf(s, args...)
|
||||
}
|
||||
|
||||
func (l LogrusStdWrapper) Panicln(args ...interface{}) {
|
||||
l.logger.Panic().CallerSkipFrame(1).MsgFunc(msgFunc(args...))
|
||||
}
|
17
pkg/logs/logrus_test.go
Normal file
17
pkg/logs/logrus_test.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func TestNewLogrusStdWrapper(t *testing.T) {
|
||||
out := zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}
|
||||
|
||||
logger := NewLogrusWrapper(zerolog.New(out).With().Caller().Logger())
|
||||
|
||||
logger.Println("foo")
|
||||
}
|
27
pkg/logs/oxy.go
Normal file
27
pkg/logs/oxy.go
Normal file
|
@ -0,0 +1,27 @@
|
|||
package logs
|
||||
|
||||
import "github.com/rs/zerolog"
|
||||
|
||||
type OxyWrapper struct {
|
||||
logger zerolog.Logger
|
||||
}
|
||||
|
||||
func NewOxyWrapper(logger zerolog.Logger) *OxyWrapper {
|
||||
return &OxyWrapper{logger: logger}
|
||||
}
|
||||
|
||||
func (l OxyWrapper) Debug(s string, i ...interface{}) {
|
||||
l.logger.Debug().CallerSkipFrame(1).Msgf(s, i...)
|
||||
}
|
||||
|
||||
func (l OxyWrapper) Info(s string, i ...interface{}) {
|
||||
l.logger.Info().CallerSkipFrame(1).Msgf(s, i...)
|
||||
}
|
||||
|
||||
func (l OxyWrapper) Warn(s string, i ...interface{}) {
|
||||
l.logger.Warn().CallerSkipFrame(1).Msgf(s, i...)
|
||||
}
|
||||
|
||||
func (l OxyWrapper) Error(s string, i ...interface{}) {
|
||||
l.logger.Error().CallerSkipFrame(1).Msgf(s, i...)
|
||||
}
|
17
pkg/logs/oxy_test.go
Normal file
17
pkg/logs/oxy_test.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package logs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func TestNewOxyWrapper(t *testing.T) {
|
||||
out := zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}
|
||||
|
||||
logger := NewOxyWrapper(zerolog.New(out).With().Caller().Logger())
|
||||
|
||||
logger.Info("foo")
|
||||
}
|
|
@ -4,9 +4,9 @@ import (
|
|||
"context"
|
||||
"time"
|
||||
|
||||
kitlog "github.com/go-kit/kit/log"
|
||||
"github.com/go-kit/kit/metrics/dogstatsd"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/safe"
|
||||
"github.com/traefik/traefik/v2/pkg/types"
|
||||
)
|
||||
|
@ -58,10 +58,7 @@ func RegisterDatadog(ctx context.Context, config *types.Datadog) Registry {
|
|||
config.Prefix = defaultMetricsPrefix
|
||||
}
|
||||
|
||||
datadogClient = dogstatsd.New(config.Prefix+".", kitlog.LoggerFunc(func(keyvals ...interface{}) error {
|
||||
log.WithoutContext().WithField(log.MetricsProviderName, "datadog").Info(keyvals...)
|
||||
return nil
|
||||
}))
|
||||
datadogClient = dogstatsd.New(config.Prefix+".", logs.NewGoKitWrapper(log.Logger.With().Str(logs.MetricsProviderName, "datadog").Logger()))
|
||||
|
||||
initDatadogClient(ctx, config)
|
||||
|
||||
|
|
|
@ -8,10 +8,10 @@ import (
|
|||
"regexp"
|
||||
"time"
|
||||
|
||||
kitlog "github.com/go-kit/kit/log"
|
||||
"github.com/go-kit/kit/metrics/influx"
|
||||
influxdb "github.com/influxdata/influxdb1-client/v2"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/safe"
|
||||
"github.com/traefik/traefik/v2/pkg/types"
|
||||
)
|
||||
|
@ -112,30 +112,30 @@ func RegisterInfluxDB(ctx context.Context, config *types.InfluxDB) Registry {
|
|||
|
||||
// initInfluxDBClient creates a influxDBClient.
|
||||
func initInfluxDBClient(ctx context.Context, config *types.InfluxDB) *influx.Influx {
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
// TODO deprecated: move this switch into configuration.SetEffectiveConfiguration when web provider will be removed.
|
||||
switch config.Protocol {
|
||||
case protocolUDP:
|
||||
if len(config.Database) > 0 || len(config.RetentionPolicy) > 0 {
|
||||
logger.Warn("Database and RetentionPolicy options have no effect with UDP.")
|
||||
logger.Warn().Msg("Database and RetentionPolicy options have no effect with UDP.")
|
||||
config.Database = ""
|
||||
config.RetentionPolicy = ""
|
||||
}
|
||||
case protocolHTTP:
|
||||
if u, err := url.Parse(config.Address); err == nil {
|
||||
if u.Scheme != "http" && u.Scheme != "https" {
|
||||
logger.Warnf("InfluxDB address %s should specify a scheme (http or https): falling back on HTTP.", config.Address)
|
||||
logger.Warn().Msgf("InfluxDB address %s should specify a scheme (http or https): falling back on HTTP.", config.Address)
|
||||
config.Address = "http://" + config.Address
|
||||
}
|
||||
} else {
|
||||
logger.Errorf("Unable to parse the InfluxDB address %v: falling back on UDP.", err)
|
||||
logger.Error().Err(err).Msg("Unable to parse the InfluxDB address: falling back on UDP.")
|
||||
config.Protocol = protocolUDP
|
||||
config.Database = ""
|
||||
config.RetentionPolicy = ""
|
||||
}
|
||||
default:
|
||||
logger.Warnf("Unsupported protocol %s: falling back on UDP.", config.Protocol)
|
||||
logger.Warn().Msgf("Unsupported protocol %s: falling back on UDP.", config.Protocol)
|
||||
config.Protocol = protocolUDP
|
||||
config.Database = ""
|
||||
config.RetentionPolicy = ""
|
||||
|
@ -147,10 +147,8 @@ func initInfluxDBClient(ctx context.Context, config *types.InfluxDB) *influx.Inf
|
|||
Database: config.Database,
|
||||
RetentionPolicy: config.RetentionPolicy,
|
||||
},
|
||||
kitlog.LoggerFunc(func(keyvals ...interface{}) error {
|
||||
log.WithoutContext().WithField(log.MetricsProviderName, "influxdb").Info(keyvals...)
|
||||
return nil
|
||||
}))
|
||||
logs.NewGoKitWrapper(*logger),
|
||||
)
|
||||
}
|
||||
|
||||
// initInfluxDBTicker initializes metrics pusher.
|
||||
|
@ -190,10 +188,10 @@ func (w *influxDBWriter) Write(bp influxdb.BatchPoints) error {
|
|||
defer c.Close()
|
||||
|
||||
if writeErr := c.Write(bp); writeErr != nil {
|
||||
ctx := log.With(context.Background(), log.Str(log.MetricsProviderName, "influxdb"))
|
||||
log.FromContext(ctx).Errorf("Error while writing to InfluxDB: %s", writeErr.Error())
|
||||
logger := log.With().Str(logs.MetricsProviderName, "influxdb").Logger()
|
||||
logger.Error().Err(writeErr).Msg("Error while writing to InfluxDB")
|
||||
|
||||
if handleErr := w.handleWriteError(ctx, c, writeErr); handleErr != nil {
|
||||
if handleErr := w.handleWriteError(logger.WithContext(context.Background()), c, writeErr); handleErr != nil {
|
||||
return handleErr
|
||||
}
|
||||
// Retry write after successful handling of writeErr
|
||||
|
@ -232,9 +230,9 @@ func (w *influxDBWriter) handleWriteError(ctx context.Context, c influxdb.Client
|
|||
qStr = fmt.Sprintf("%s WITH NAME \"%s\"", qStr, w.config.RetentionPolicy)
|
||||
}
|
||||
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
logger.Debugf("InfluxDB database not found: attempting to create one with %s", qStr)
|
||||
logger.Debug().Msgf("InfluxDB database not found: attempting to create one with %s", qStr)
|
||||
|
||||
q := influxdb.NewQuery(qStr, "", "")
|
||||
response, queryErr := c.Query(q)
|
||||
|
@ -242,10 +240,10 @@ func (w *influxDBWriter) handleWriteError(ctx context.Context, c influxdb.Client
|
|||
queryErr = response.Error()
|
||||
}
|
||||
if queryErr != nil {
|
||||
logger.Errorf("Error while creating the InfluxDB database %s", queryErr)
|
||||
logger.Error().Err(queryErr).Msg("Error while creating the InfluxDB database")
|
||||
return queryErr
|
||||
}
|
||||
|
||||
logger.Debugf("Successfully created the InfluxDB database %s", w.config.Database)
|
||||
logger.Debug().Msgf("Successfully created the InfluxDB database %s", w.config.Database)
|
||||
return nil
|
||||
}
|
||||
|
|
|
@ -5,14 +5,14 @@ import (
|
|||
"errors"
|
||||
"time"
|
||||
|
||||
kitlog "github.com/go-kit/kit/log"
|
||||
"github.com/go-kit/kit/metrics/influx"
|
||||
influxdb2 "github.com/influxdata/influxdb-client-go/v2"
|
||||
influxdb2api "github.com/influxdata/influxdb-client-go/v2/api"
|
||||
"github.com/influxdata/influxdb-client-go/v2/api/write"
|
||||
influxdb2log "github.com/influxdata/influxdb-client-go/v2/log"
|
||||
influxdb "github.com/influxdata/influxdb1-client/v2"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/safe"
|
||||
"github.com/traefik/traefik/v2/pkg/types"
|
||||
)
|
||||
|
@ -25,10 +25,12 @@ var (
|
|||
|
||||
// RegisterInfluxDB2 creates metrics exporter for InfluxDB2.
|
||||
func RegisterInfluxDB2(ctx context.Context, config *types.InfluxDB2) Registry {
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
if influxDB2Client == nil {
|
||||
var err error
|
||||
if influxDB2Client, err = newInfluxDB2Client(config); err != nil {
|
||||
log.FromContext(ctx).Error(err)
|
||||
logger.Error().Err(err).Send()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
@ -37,10 +39,7 @@ func RegisterInfluxDB2(ctx context.Context, config *types.InfluxDB2) Registry {
|
|||
influxDB2Store = influx.New(
|
||||
config.AdditionalLabels,
|
||||
influxdb.BatchPointsConfig{},
|
||||
kitlog.LoggerFunc(func(kv ...interface{}) error {
|
||||
log.FromContext(ctx).Error(kv...)
|
||||
return nil
|
||||
}),
|
||||
logs.NewGoKitWrapper(*logger),
|
||||
)
|
||||
|
||||
influxDB2Ticker = time.NewTicker(time.Duration(config.PushInterval))
|
||||
|
@ -127,14 +126,13 @@ type influxDB2Writer struct {
|
|||
}
|
||||
|
||||
func (w influxDB2Writer) Write(bp influxdb.BatchPoints) error {
|
||||
ctx := log.With(context.Background(), log.Str(log.MetricsProviderName, "influxdb2"))
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.With().Str(logs.MetricsProviderName, "influxdb2").Logger()
|
||||
|
||||
wps := make([]*write.Point, 0, len(bp.Points()))
|
||||
for _, p := range bp.Points() {
|
||||
fields, err := p.Fields()
|
||||
if err != nil {
|
||||
logger.Errorf("Error while getting %s point fields: %s", p.Name(), err)
|
||||
logger.Error().Err(err).Msgf("Error while getting %s point fields", p.Name())
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -146,5 +144,7 @@ func (w influxDB2Writer) Write(bp influxdb.BatchPoints) error {
|
|||
))
|
||||
}
|
||||
|
||||
ctx := logger.WithContext(context.Background())
|
||||
|
||||
return w.wc.WritePoint(ctx, wps...)
|
||||
}
|
||||
|
|
|
@ -11,8 +11,8 @@ import (
|
|||
stdprometheus "github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/types"
|
||||
)
|
||||
|
||||
|
@ -90,14 +90,14 @@ func RegisterPrometheus(ctx context.Context, config *types.Prometheus) Registry
|
|||
if err := promRegistry.Register(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})); err != nil {
|
||||
var arErr stdprometheus.AlreadyRegisteredError
|
||||
if !errors.As(err, &arErr) {
|
||||
log.FromContext(ctx).Warn("ProcessCollector is already registered")
|
||||
log.Ctx(ctx).Warn().Msg("ProcessCollector is already registered")
|
||||
}
|
||||
}
|
||||
|
||||
if err := promRegistry.Register(collectors.NewGoCollector()); err != nil {
|
||||
var arErr stdprometheus.AlreadyRegisteredError
|
||||
if !errors.As(err, &arErr) {
|
||||
log.FromContext(ctx).Warn("GoCollector is already registered")
|
||||
log.Ctx(ctx).Warn().Msg("GoCollector is already registered")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -306,15 +306,15 @@ func registerPromState(ctx context.Context) bool {
|
|||
return true
|
||||
}
|
||||
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
var arErr stdprometheus.AlreadyRegisteredError
|
||||
if errors.As(err, &arErr) {
|
||||
logger.Debug("Prometheus collector already registered.")
|
||||
logger.Debug().Msg("Prometheus collector already registered.")
|
||||
return true
|
||||
}
|
||||
|
||||
logger.Errorf("Unable to register Traefik to Prometheus: %v", err)
|
||||
logger.Error().Err(err).Msg("Unable to register Traefik to Prometheus")
|
||||
return false
|
||||
}
|
||||
|
||||
|
|
|
@ -4,9 +4,9 @@ import (
|
|||
"context"
|
||||
"time"
|
||||
|
||||
kitlog "github.com/go-kit/kit/log"
|
||||
"github.com/go-kit/kit/metrics/statsd"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/safe"
|
||||
"github.com/traefik/traefik/v2/pkg/types"
|
||||
)
|
||||
|
@ -55,10 +55,7 @@ func RegisterStatsd(ctx context.Context, config *types.Statsd) Registry {
|
|||
config.Prefix = defaultMetricsPrefix
|
||||
}
|
||||
|
||||
statsdClient = statsd.New(config.Prefix+".", kitlog.LoggerFunc(func(keyvals ...interface{}) error {
|
||||
log.WithoutContext().WithField(log.MetricsProviderName, "statsd").Info(keyvals...)
|
||||
return nil
|
||||
}))
|
||||
statsdClient = statsd.New(config.Prefix+".", logs.NewGoKitWrapper(*log.Ctx(ctx)))
|
||||
|
||||
if statsdTicker == nil {
|
||||
statsdTicker = initStatsdTicker(ctx, config)
|
||||
|
|
|
@ -4,9 +4,10 @@ import (
|
|||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares/capture"
|
||||
"github.com/vulcand/oxy/utils"
|
||||
"github.com/vulcand/oxy/v2/utils"
|
||||
)
|
||||
|
||||
// FieldApply function hook to add data in accesslog.
|
||||
|
@ -57,7 +58,7 @@ func AddOriginFields(rw http.ResponseWriter, req *http.Request, next http.Handle
|
|||
ctx := req.Context()
|
||||
capt, err := capture.FromContext(ctx)
|
||||
if err != nil {
|
||||
log.FromContext(log.With(ctx, log.Str(log.MiddlewareType, "AccessLogs"))).Errorf("Could not get Capture: %v", err)
|
||||
log.Ctx(ctx).Error().Err(err).Str(logs.MiddlewareType, "AccessLogs").Msg("Could not get Capture")
|
||||
return
|
||||
}
|
||||
|
||||
|
|
|
@ -16,9 +16,10 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/containous/alice"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/sirupsen/logrus"
|
||||
ptypes "github.com/traefik/paerser/types"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares/capture"
|
||||
traefiktls "github.com/traefik/traefik/v2/pkg/tls"
|
||||
"github.com/traefik/traefik/v2/pkg/types"
|
||||
|
@ -94,7 +95,7 @@ func NewHandler(config *types.AccessLog) (*Handler, error) {
|
|||
case JSONFormat:
|
||||
formatter = new(logrus.JSONFormatter)
|
||||
default:
|
||||
log.WithoutContext().Errorf("unsupported access log format: %q, defaulting to common format instead.", config.Format)
|
||||
log.Error().Msgf("Unsupported access log format: %q, defaulting to common format instead.", config.Format)
|
||||
formatter = new(CommonLogFormatter)
|
||||
}
|
||||
|
||||
|
@ -125,7 +126,7 @@ func NewHandler(config *types.AccessLog) (*Handler, error) {
|
|||
|
||||
if config.Filters != nil {
|
||||
if httpCodeRanges, err := types.NewHTTPCodeRanges(config.Filters.StatusCodes); err != nil {
|
||||
log.WithoutContext().Errorf("Failed to create new HTTP code ranges: %s", err)
|
||||
log.Error().Err(err).Msg("Failed to create new HTTP code ranges")
|
||||
} else {
|
||||
logHandler.httpCodeRanges = httpCodeRanges
|
||||
}
|
||||
|
@ -233,9 +234,7 @@ func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request, next http
|
|||
ctx := req.Context()
|
||||
capt, err := capture.FromContext(ctx)
|
||||
if err != nil {
|
||||
log.FromContext(log.With(ctx, log.Str(log.MiddlewareType, "AccessLogs"))).
|
||||
WithError(err).
|
||||
Errorf("Could not get Capture")
|
||||
log.Ctx(ctx).Error().Err(err).Str(logs.MiddlewareType, "AccessLogs").Msg("Could not get Capture")
|
||||
return
|
||||
}
|
||||
|
||||
|
|
|
@ -7,7 +7,6 @@ import (
|
|||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
)
|
||||
|
@ -25,7 +24,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) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
|
||||
var result *addPrefix
|
||||
|
||||
if len(config.Prefix) > 0 {
|
||||
|
@ -46,16 +45,16 @@ func (a *addPrefix) GetTracingInformation() (string, ext.SpanKindEnum) {
|
|||
}
|
||||
|
||||
func (a *addPrefix) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), a.name, typeName))
|
||||
logger := middlewares.GetLogger(req.Context(), a.name, typeName)
|
||||
|
||||
oldURLPath := req.URL.Path
|
||||
req.URL.Path = ensureLeadingSlash(a.prefix + req.URL.Path)
|
||||
logger.Debugf("URL.Path is now %s (was %s).", req.URL.Path, oldURLPath)
|
||||
logger.Debug().Msgf("URL.Path is now %s (was %s).", req.URL.Path, oldURLPath)
|
||||
|
||||
if req.URL.RawPath != "" {
|
||||
oldURLRawPath := req.URL.RawPath
|
||||
req.URL.RawPath = ensureLeadingSlash(a.prefix + req.URL.RawPath)
|
||||
logger.Debugf("URL.RawPath is now %s (was %s).", req.URL.RawPath, oldURLRawPath)
|
||||
logger.Debug().Msgf("URL.RawPath is now %s (was %s).", req.URL.RawPath, oldURLRawPath)
|
||||
}
|
||||
req.RequestURI = req.URL.RequestURI()
|
||||
|
||||
|
|
|
@ -10,7 +10,6 @@ import (
|
|||
goauth "github.com/abbot/go-http-auth"
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares/accesslog"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
|
@ -31,7 +30,8 @@ type basicAuth struct {
|
|||
|
||||
// NewBasic creates a basicAuth middleware.
|
||||
func NewBasic(ctx context.Context, next http.Handler, authConfig dynamic.BasicAuth, name string) (http.Handler, error) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, basicTypeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, basicTypeName).Debug().Msg("Creating middleware")
|
||||
|
||||
users, err := getUsers(authConfig.UsersFile, authConfig.Users, basicUserParser)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -60,7 +60,7 @@ func (b *basicAuth) GetTracingInformation() (string, ext.SpanKindEnum) {
|
|||
}
|
||||
|
||||
func (b *basicAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), b.name, basicTypeName))
|
||||
logger := middlewares.GetLogger(req.Context(), b.name, basicTypeName)
|
||||
|
||||
user, password, ok := req.BasicAuth()
|
||||
if ok {
|
||||
|
@ -76,14 +76,14 @@ func (b *basicAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
}
|
||||
|
||||
if !ok {
|
||||
logger.Debug("Authentication failed")
|
||||
logger.Debug().Msg("Authentication failed")
|
||||
tracing.SetErrorWithEvent(req, "Authentication failed")
|
||||
|
||||
b.auth.RequireAuth(rw, req)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Debug("Authentication succeeded")
|
||||
logger.Debug().Msg("Authentication succeeded")
|
||||
req.URL.User = url.User(user)
|
||||
|
||||
if b.headerField != "" {
|
||||
|
@ -91,7 +91,7 @@ func (b *basicAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
}
|
||||
|
||||
if b.removeHeader {
|
||||
logger.Debug("Removing authorization header")
|
||||
logger.Debug().Msg("Removing authorization header")
|
||||
req.Header.Del(authorizationHeader)
|
||||
}
|
||||
b.next.ServeHTTP(rw, req)
|
||||
|
|
|
@ -10,7 +10,6 @@ import (
|
|||
goauth "github.com/abbot/go-http-auth"
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares/accesslog"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
|
@ -31,7 +30,8 @@ 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) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, digestTypeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, digestTypeName).Debug().Msg("Creating middleware")
|
||||
|
||||
users, err := getUsers(authConfig.UsersFile, authConfig.Users, digestUserParser)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -59,7 +59,7 @@ func (d *digestAuth) GetTracingInformation() (string, ext.SpanKindEnum) {
|
|||
}
|
||||
|
||||
func (d *digestAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), d.name, digestTypeName))
|
||||
logger := middlewares.GetLogger(req.Context(), d.name, digestTypeName)
|
||||
|
||||
username, authinfo := d.auth.CheckAuth(req)
|
||||
if username == "" {
|
||||
|
@ -77,19 +77,19 @@ func (d *digestAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
}
|
||||
|
||||
if authinfo != nil && *authinfo == "stale" {
|
||||
logger.Debug("Digest authentication failed, possibly because out of order requests")
|
||||
logger.Debug().Msg("Digest authentication failed, possibly because out of order requests")
|
||||
tracing.SetErrorWithEvent(req, "Digest authentication failed, possibly because out of order requests")
|
||||
d.auth.RequireAuthStale(rw, req)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Debug("Digest authentication failed")
|
||||
logger.Debug().Msg("Digest authentication failed")
|
||||
tracing.SetErrorWithEvent(req, "Digest authentication failed")
|
||||
d.auth.RequireAuth(rw, req)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Debug("Digest authentication succeeded")
|
||||
logger.Debug().Msg("Digest authentication succeeded")
|
||||
req.URL.User = url.User(username)
|
||||
|
||||
logData := accesslog.GetLogData(req)
|
||||
|
@ -102,7 +102,7 @@ func (d *digestAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
}
|
||||
|
||||
if d.removeHeader {
|
||||
logger.Debug("Removing the Authorization header")
|
||||
logger.Debug().Msg("Removing the Authorization header")
|
||||
req.Header.Del(authorizationHeader)
|
||||
}
|
||||
d.next.ServeHTTP(rw, req)
|
||||
|
|
|
@ -13,12 +13,11 @@ import (
|
|||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares/connectionheader"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
"github.com/vulcand/oxy/forward"
|
||||
"github.com/vulcand/oxy/utils"
|
||||
"github.com/vulcand/oxy/v2/forward"
|
||||
"github.com/vulcand/oxy/v2/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -52,7 +51,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) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, forwardedTypeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, forwardedTypeName).Debug().Msg("Creating middleware")
|
||||
|
||||
fa := &forwardAuth{
|
||||
address: config.Address,
|
||||
|
@ -98,13 +97,13 @@ func (fa *forwardAuth) GetTracingInformation() (string, ext.SpanKindEnum) {
|
|||
}
|
||||
|
||||
func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), fa.name, forwardedTypeName))
|
||||
logger := middlewares.GetLogger(req.Context(), fa.name, forwardedTypeName)
|
||||
|
||||
forwardReq, err := http.NewRequest(http.MethodGet, fa.address, nil)
|
||||
tracing.LogRequest(tracing.GetSpan(req), forwardReq)
|
||||
if err != nil {
|
||||
logMessage := fmt.Sprintf("Error calling %s. Cause %s", fa.address, err)
|
||||
logger.Debug(logMessage)
|
||||
logger.Debug().Msg(logMessage)
|
||||
tracing.SetErrorWithEvent(req, logMessage)
|
||||
|
||||
rw.WriteHeader(http.StatusInternalServerError)
|
||||
|
@ -120,7 +119,7 @@ func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
forwardResponse, forwardErr := fa.client.Do(forwardReq)
|
||||
if forwardErr != nil {
|
||||
logMessage := fmt.Sprintf("Error calling %s. Cause: %s", fa.address, forwardErr)
|
||||
logger.Debug(logMessage)
|
||||
logger.Debug().Msg(logMessage)
|
||||
tracing.SetErrorWithEvent(req, logMessage)
|
||||
|
||||
rw.WriteHeader(http.StatusInternalServerError)
|
||||
|
@ -130,7 +129,7 @@ func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
body, readError := io.ReadAll(forwardResponse.Body)
|
||||
if readError != nil {
|
||||
logMessage := fmt.Sprintf("Error reading body %s. Cause: %s", fa.address, readError)
|
||||
logger.Debug(logMessage)
|
||||
logger.Debug().Msg(logMessage)
|
||||
tracing.SetErrorWithEvent(req, logMessage)
|
||||
|
||||
rw.WriteHeader(http.StatusInternalServerError)
|
||||
|
@ -141,7 +140,7 @@ func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
// Pass the forward response's body and selected headers if it
|
||||
// didn't return a response within the range of [200, 300).
|
||||
if forwardResponse.StatusCode < http.StatusOK || forwardResponse.StatusCode >= http.StatusMultipleChoices {
|
||||
logger.Debugf("Remote error %s. StatusCode: %d", fa.address, forwardResponse.StatusCode)
|
||||
logger.Debug().Msgf("Remote error %s. StatusCode: %d", fa.address, forwardResponse.StatusCode)
|
||||
|
||||
utils.CopyHeaders(rw.Header(), forwardResponse.Header)
|
||||
utils.RemoveHeaders(rw.Header(), hopHeaders...)
|
||||
|
@ -152,7 +151,7 @@ func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
if err != nil {
|
||||
if !errors.Is(err, http.ErrNoLocation) {
|
||||
logMessage := fmt.Sprintf("Error reading response location header %s. Cause: %s", fa.address, err)
|
||||
logger.Debug(logMessage)
|
||||
logger.Debug().Msg(logMessage)
|
||||
tracing.SetErrorWithEvent(req, logMessage)
|
||||
|
||||
rw.WriteHeader(http.StatusInternalServerError)
|
||||
|
@ -167,7 +166,7 @@ func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
rw.WriteHeader(forwardResponse.StatusCode)
|
||||
|
||||
if _, err = rw.Write(body); err != nil {
|
||||
logger.Error(err)
|
||||
logger.Error().Err(err).Send()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
|
|
@ -16,7 +16,7 @@ import (
|
|||
tracingMiddleware "github.com/traefik/traefik/v2/pkg/middlewares/tracing"
|
||||
"github.com/traefik/traefik/v2/pkg/testhelpers"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
"github.com/vulcand/oxy/forward"
|
||||
"github.com/vulcand/oxy/v2/forward"
|
||||
)
|
||||
|
||||
func TestForwardAuthFail(t *testing.T) {
|
||||
|
|
|
@ -5,11 +5,12 @@ import (
|
|||
"net/http"
|
||||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
oxybuffer "github.com/vulcand/oxy/buffer"
|
||||
oxybuffer "github.com/vulcand/oxy/v2/buffer"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -23,9 +24,9 @@ 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 := 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'",
|
||||
logger := middlewares.GetLogger(ctx, name, typeName)
|
||||
logger.Debug().Msg("Creating middleware")
|
||||
logger.Debug().Msgf("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)
|
||||
|
||||
oxyBuffer, err := oxybuffer.New(
|
||||
|
@ -34,7 +35,9 @@ func New(ctx context.Context, next http.Handler, config dynamic.Buffering, name
|
|||
oxybuffer.MaxRequestBodyBytes(config.MaxRequestBodyBytes),
|
||||
oxybuffer.MemResponseBodyBytes(config.MemResponseBodyBytes),
|
||||
oxybuffer.MaxResponseBodyBytes(config.MaxResponseBodyBytes),
|
||||
oxybuffer.CondSetter(len(config.RetryExpression) > 0, oxybuffer.Retry(config.RetryExpression)),
|
||||
oxybuffer.Logger(logs.NewOxyWrapper(*logger)),
|
||||
oxybuffer.Verbose(logger.GetLevel() == zerolog.TraceLevel),
|
||||
oxybuffer.Cond(len(config.RetryExpression) > 0, oxybuffer.Retry(config.RetryExpression)),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
|
@ -6,7 +6,6 @@ import (
|
|||
|
||||
"github.com/containous/alice"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
)
|
||||
|
||||
|
@ -20,7 +19,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) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
|
||||
|
||||
middlewareChain := builder.BuildChain(ctx, config.Middlewares)
|
||||
return middlewareChain.Then(next)
|
||||
|
|
|
@ -6,11 +6,13 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
"github.com/vulcand/oxy/cbreaker"
|
||||
"github.com/vulcand/oxy/v2/cbreaker"
|
||||
)
|
||||
|
||||
const typeName = "CircuitBreaker"
|
||||
|
@ -24,19 +26,21 @@ type circuitBreaker struct {
|
|||
func New(ctx context.Context, next http.Handler, confCircuitBreaker dynamic.CircuitBreaker, name string) (http.Handler, error) {
|
||||
expression := confCircuitBreaker.Expression
|
||||
|
||||
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
|
||||
logger.Debug("Creating middleware")
|
||||
logger.Debugf("Setting up with expression: %s", expression)
|
||||
logger := middlewares.GetLogger(ctx, name, typeName)
|
||||
logger.Debug().Msg("Creating middleware")
|
||||
logger.Debug().Msgf("Setting up with expression: %s", expression)
|
||||
|
||||
cbOpts := []cbreaker.CircuitBreakerOption{
|
||||
cbOpts := []cbreaker.Option{
|
||||
cbreaker.Fallback(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
|
||||
tracing.SetErrorWithEvent(req, "blocked by circuit-breaker (%q)", expression)
|
||||
rw.WriteHeader(http.StatusServiceUnavailable)
|
||||
|
||||
if _, err := rw.Write([]byte(http.StatusText(http.StatusServiceUnavailable))); err != nil {
|
||||
log.FromContext(req.Context()).Error(err)
|
||||
log.Ctx(req.Context()).Error().Err(err).Send()
|
||||
}
|
||||
})),
|
||||
cbreaker.Logger(logs.NewOxyWrapper(*logger)),
|
||||
cbreaker.Verbose(logger.GetLevel() == zerolog.TraceLevel),
|
||||
}
|
||||
|
||||
if confCircuitBreaker.CheckPeriod > 0 {
|
||||
|
@ -55,6 +59,7 @@ func New(ctx context.Context, next http.Handler, confCircuitBreaker dynamic.Circ
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &circuitBreaker{
|
||||
circuitBreaker: oxyCircuitBreaker,
|
||||
name: name,
|
||||
|
|
|
@ -10,7 +10,6 @@ import (
|
|||
"github.com/klauspost/compress/gzhttp"
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares/compress/brotli"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
|
@ -35,7 +34,7 @@ type compress struct {
|
|||
|
||||
// New creates a new compress middleware.
|
||||
func New(ctx context.Context, next http.Handler, conf dynamic.Compress, name string) (http.Handler, error) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
|
||||
|
||||
excludes := []string{"application/grpc"}
|
||||
for _, v := range conf.ExcludedContentTypes {
|
||||
|
@ -74,7 +73,7 @@ func New(ctx context.Context, next http.Handler, conf dynamic.Compress, name str
|
|||
}
|
||||
|
||||
func (c *compress) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), c.name, typeName))
|
||||
logger := middlewares.GetLogger(req.Context(), c.name, typeName)
|
||||
|
||||
if req.Method == http.MethodHead {
|
||||
c.next.ServeHTTP(rw, req)
|
||||
|
@ -83,7 +82,7 @@ func (c *compress) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
|
||||
mediaType, _, err := mime.ParseMediaType(req.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
logger.WithError(err).Debug("Unable to parse MIME type")
|
||||
logger.Debug().Err(err).Msg("Unable to parse MIME type")
|
||||
}
|
||||
|
||||
// Notably for text/event-stream requests the response should not be compressed.
|
||||
|
|
|
@ -12,11 +12,10 @@ import (
|
|||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
"github.com/traefik/traefik/v2/pkg/types"
|
||||
"github.com/vulcand/oxy/utils"
|
||||
"github.com/vulcand/oxy/v2/utils"
|
||||
)
|
||||
|
||||
// Compile time validation that the response recorder implements http interfaces correctly.
|
||||
|
@ -42,7 +41,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) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
|
||||
|
||||
httpCodeRanges, err := types.NewHTTPCodeRanges(config.Status)
|
||||
if err != nil {
|
||||
|
@ -68,11 +67,10 @@ func (c *customErrors) GetTracingInformation() (string, ext.SpanKindEnum) {
|
|||
}
|
||||
|
||||
func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
ctx := middlewares.GetLoggerCtx(req.Context(), c.name, typeName)
|
||||
logger := log.FromContext(ctx)
|
||||
logger := middlewares.GetLogger(req.Context(), c.name, typeName)
|
||||
|
||||
if c.backendHandler == nil {
|
||||
logger.Error("Error pages: no backend handler.")
|
||||
logger.Error().Msg("Error pages: no backend handler.")
|
||||
tracing.SetErrorWithEvent(req, "Error pages: no backend handler.")
|
||||
c.next.ServeHTTP(rw, req)
|
||||
return
|
||||
|
@ -86,7 +84,7 @@ func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
|
||||
// check the recorder code against the configured http status code ranges
|
||||
code := catcher.getCode()
|
||||
logger.Debugf("Caught HTTP Status Code %d, returning error page", code)
|
||||
logger.Debug().Msgf("Caught HTTP Status Code %d, returning error page", code)
|
||||
|
||||
var query string
|
||||
if len(c.backendQuery) > 0 {
|
||||
|
@ -97,7 +95,7 @@ func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
|
||||
pageReq, err := newRequest("http://" + req.Host + query)
|
||||
if err != nil {
|
||||
logger.Error(err)
|
||||
logger.Error().Err(err).Send()
|
||||
http.Error(rw, http.StatusText(code), code)
|
||||
return
|
||||
}
|
||||
|
|
|
@ -6,9 +6,9 @@ import (
|
|||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/vulcand/oxy/utils"
|
||||
"github.com/vulcand/oxy/v2/utils"
|
||||
)
|
||||
|
||||
// GetSourceExtractor returns the SourceExtractor function corresponding to the given sourceMatcher.
|
||||
|
@ -35,26 +35,26 @@ func GetSourceExtractor(ctx context.Context, sourceMatcher *dynamic.SourceCriter
|
|||
}
|
||||
}
|
||||
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
if sourceMatcher.IPStrategy != nil {
|
||||
strategy, err := sourceMatcher.IPStrategy.Get()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Debug("Using IPStrategy")
|
||||
logger.Debug().Msg("Using IPStrategy")
|
||||
return utils.ExtractorFunc(func(req *http.Request) (string, int64, error) {
|
||||
return strategy.GetIP(req), 1, nil
|
||||
}), nil
|
||||
}
|
||||
|
||||
if sourceMatcher.RequestHeaderName != "" {
|
||||
logger.Debug("Using RequestHeaderName")
|
||||
logger.Debug().Msg("Using RequestHeaderName")
|
||||
return utils.NewExtractor(fmt.Sprintf("request.header.%s", sourceMatcher.RequestHeaderName))
|
||||
}
|
||||
|
||||
if sourceMatcher.RequestHost {
|
||||
logger.Debug("Using RequestHost")
|
||||
logger.Debug().Msg("Using RequestHost")
|
||||
return utils.NewExtractor("request.host")
|
||||
}
|
||||
|
||||
|
|
|
@ -6,7 +6,6 @@ import (
|
|||
|
||||
"github.com/improbable-eng/grpc-web/go/grpcweb"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
)
|
||||
|
||||
|
@ -14,7 +13,7 @@ const typeName = "grpc-web"
|
|||
|
||||
// New builds a new gRPC web request converter.
|
||||
func New(ctx context.Context, next http.Handler, config dynamic.GrpcWeb, name string) http.Handler {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
|
||||
|
||||
return grpcweb.WrapHandler(next, grpcweb.WithCorsForRegisteredEndpointsOnly(false), grpcweb.WithOriginFunc(func(origin string) bool {
|
||||
for _, originCfg := range config.AllowOrigins {
|
||||
|
|
|
@ -8,8 +8,9 @@ import (
|
|||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
)
|
||||
|
||||
// Header is a middleware that helps setup a few basic security features.
|
||||
|
@ -28,7 +29,8 @@ func NewHeader(next http.Handler, cfg dynamic.Headers) (*Header, error) {
|
|||
hasCustomHeaders := cfg.HasCustomHeadersDefined()
|
||||
hasCorsHeaders := cfg.HasCorsHeadersDefined()
|
||||
|
||||
ctx := log.With(context.Background(), log.Str(log.MiddlewareType, typeName))
|
||||
ctx := log.With().Str(logs.MiddlewareType, typeName).Logger().WithContext(context.Background())
|
||||
|
||||
handleDeprecation(ctx, &cfg)
|
||||
|
||||
regexes := make([]*regexp.Regexp, len(cfg.AccessControlAllowOriginListRegex))
|
||||
|
|
|
@ -7,8 +7,8 @@ import (
|
|||
"net/http"
|
||||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares/connectionheader"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
|
@ -19,20 +19,22 @@ const (
|
|||
)
|
||||
|
||||
func handleDeprecation(ctx context.Context, cfg *dynamic.Headers) {
|
||||
logger := log.Ctx(ctx).Warn()
|
||||
|
||||
if cfg.SSLRedirect {
|
||||
log.FromContext(ctx).Warn("SSLRedirect is deprecated, please use entrypoint redirection instead.")
|
||||
logger.Msg("SSLRedirect is deprecated, please use entrypoint redirection instead.")
|
||||
}
|
||||
if cfg.SSLTemporaryRedirect {
|
||||
log.FromContext(ctx).Warn("SSLTemporaryRedirect is deprecated, please use entrypoint redirection instead.")
|
||||
logger.Msg("SSLTemporaryRedirect is deprecated, please use entrypoint redirection instead.")
|
||||
}
|
||||
if cfg.SSLHost != "" {
|
||||
log.FromContext(ctx).Warn("SSLHost is deprecated, please use RedirectRegex middleware instead.")
|
||||
logger.Msg("SSLHost is deprecated, please use RedirectRegex middleware instead.")
|
||||
}
|
||||
if cfg.SSLForceHost {
|
||||
log.FromContext(ctx).Warn("SSLForceHost is deprecated, please use RedirectScheme middleware instead.")
|
||||
logger.Msg("SSLForceHost is deprecated, please use RedirectScheme middleware instead.")
|
||||
}
|
||||
if cfg.FeaturePolicy != "" {
|
||||
log.FromContext(ctx).Warn("FeaturePolicy is deprecated, please use PermissionsPolicy header instead.")
|
||||
logger.Msg("FeaturePolicy is deprecated, please use PermissionsPolicy header instead.")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -44,9 +46,10 @@ type headers struct {
|
|||
// New creates a Headers middleware.
|
||||
func New(ctx context.Context, next http.Handler, cfg dynamic.Headers, name string) (http.Handler, error) {
|
||||
// HeaderMiddleware -> SecureMiddleWare -> next
|
||||
mCtx := middlewares.GetLoggerCtx(ctx, name, typeName)
|
||||
logger := log.FromContext(mCtx)
|
||||
logger.Debug("Creating middleware")
|
||||
logger := middlewares.GetLogger(ctx, name, typeName)
|
||||
logger.Debug().Msg("Creating middleware")
|
||||
|
||||
mCtx := logger.WithContext(ctx)
|
||||
|
||||
handleDeprecation(mCtx, &cfg)
|
||||
|
||||
|
@ -62,13 +65,13 @@ func New(ctx context.Context, next http.Handler, cfg dynamic.Headers, name strin
|
|||
nextHandler := next
|
||||
|
||||
if hasSecureHeaders {
|
||||
logger.Debugf("Setting up secureHeaders from %v", cfg)
|
||||
logger.Debug().Msgf("Setting up secureHeaders from %v", cfg)
|
||||
handler = newSecure(next, cfg, name)
|
||||
nextHandler = handler
|
||||
}
|
||||
|
||||
if hasCustomHeaders || hasCorsHeaders {
|
||||
logger.Debugf("Setting up customHeaders/Cors from %v", cfg)
|
||||
logger.Debug().Msgf("Setting up customHeaders/Cors from %v", cfg)
|
||||
h, err := NewHeader(nextHandler, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
|
@ -6,7 +6,7 @@ import (
|
|||
"net"
|
||||
"net/http"
|
||||
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type responseModifier struct {
|
||||
|
@ -55,7 +55,7 @@ func (r *responseModifier) WriteHeader(code int) {
|
|||
// we are propagating when we are called in Write, but we're logging anyway,
|
||||
// because we could be called from another place which does not take care of
|
||||
// checking w.modifierErr.
|
||||
log.WithoutContext().Errorf("Error when applying response modifier: %v", err)
|
||||
log.Error().Err(err).Msg("Error when applying response modifier")
|
||||
r.rw.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
|
|
@ -6,11 +6,12 @@ import (
|
|||
"net/http"
|
||||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
"github.com/vulcand/oxy/connlimit"
|
||||
"github.com/vulcand/oxy/v2/connlimit"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -25,8 +26,10 @@ type inFlightReq struct {
|
|||
// New creates a max request middleware.
|
||||
// If no source criterion is provided in the config, it defaults to RequestHost.
|
||||
func New(ctx context.Context, next http.Handler, config dynamic.InFlightReq, name string) (http.Handler, error) {
|
||||
ctxLog := log.With(ctx, log.Str(log.MiddlewareName, name), log.Str(log.MiddlewareType, typeName))
|
||||
log.FromContext(ctxLog).Debug("Creating middleware")
|
||||
logger := middlewares.GetLogger(ctx, name, typeName)
|
||||
logger.Debug().Msg("Creating middleware")
|
||||
|
||||
ctxLog := logger.WithContext(ctx)
|
||||
|
||||
if config.SourceCriterion == nil ||
|
||||
config.SourceCriterion.IPStrategy == nil &&
|
||||
|
@ -41,7 +44,9 @@ func New(ctx context.Context, next http.Handler, config dynamic.InFlightReq, nam
|
|||
return nil, fmt.Errorf("error creating requests limiter: %w", err)
|
||||
}
|
||||
|
||||
handler, err := connlimit.New(next, sourceMatcher, config.Amount)
|
||||
handler, err := connlimit.New(next, sourceMatcher, config.Amount,
|
||||
connlimit.Logger(logs.NewOxyWrapper(*logger)),
|
||||
connlimit.Verbose(logger.GetLevel() == zerolog.TraceLevel))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error creating connection limit: %w", err)
|
||||
}
|
||||
|
|
|
@ -7,9 +7,9 @@ import (
|
|||
"net/http"
|
||||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/ip"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
)
|
||||
|
@ -28,8 +28,8 @@ type ipAllowLister struct {
|
|||
|
||||
// New builds a new IPAllowLister given a list of CIDR-Strings to allow.
|
||||
func New(ctx context.Context, next http.Handler, config dynamic.IPAllowList, name string) (http.Handler, error) {
|
||||
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
|
||||
logger.Debug("Creating middleware")
|
||||
logger := middlewares.GetLogger(ctx, name, typeName)
|
||||
logger.Debug().Msg("Creating middleware")
|
||||
|
||||
if len(config.SourceRange) == 0 {
|
||||
return nil, errors.New("sourceRange is empty, IPAllowLister not created")
|
||||
|
@ -45,7 +45,7 @@ func New(ctx context.Context, next http.Handler, config dynamic.IPAllowList, nam
|
|||
return nil, err
|
||||
}
|
||||
|
||||
logger.Debugf("Setting up IPAllowLister with sourceRange: %s", config.SourceRange)
|
||||
logger.Debug().Msgf("Setting up IPAllowLister with sourceRange: %s", config.SourceRange)
|
||||
|
||||
return &ipAllowLister{
|
||||
strategy: strategy,
|
||||
|
@ -60,19 +60,19 @@ func (al *ipAllowLister) GetTracingInformation() (string, ext.SpanKindEnum) {
|
|||
}
|
||||
|
||||
func (al *ipAllowLister) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
ctx := middlewares.GetLoggerCtx(req.Context(), al.name, typeName)
|
||||
logger := log.FromContext(ctx)
|
||||
logger := middlewares.GetLogger(req.Context(), al.name, typeName)
|
||||
ctx := logger.WithContext(req.Context())
|
||||
|
||||
clientIP := al.strategy.GetIP(req)
|
||||
err := al.allowLister.IsAuthorized(clientIP)
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("Rejecting IP %s: %v", clientIP, err)
|
||||
logger.Debug(msg)
|
||||
logger.Debug().Msg(msg)
|
||||
tracing.SetErrorWithEvent(req, msg)
|
||||
reject(ctx, rw)
|
||||
return
|
||||
}
|
||||
logger.Debugf("Accepting IP %s", clientIP)
|
||||
logger.Debug().Msgf("Accepting IP %s", clientIP)
|
||||
|
||||
al.next.ServeHTTP(rw, req)
|
||||
}
|
||||
|
@ -83,6 +83,6 @@ func reject(ctx context.Context, rw http.ResponseWriter) {
|
|||
rw.WriteHeader(statusCode)
|
||||
_, err := rw.Write([]byte(http.StatusText(statusCode)))
|
||||
if err != nil {
|
||||
log.FromContext(ctx).Error(err)
|
||||
log.Ctx(ctx).Error().Err(err).Send()
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,7 +10,7 @@ import (
|
|||
|
||||
"github.com/containous/alice"
|
||||
gokitmetrics "github.com/go-kit/kit/metrics"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/metrics"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares/capture"
|
||||
|
@ -44,7 +44,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 {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, nameEntrypoint, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, nameEntrypoint, typeName).Debug().Msg("Creating middleware")
|
||||
|
||||
return &metricsMiddleware{
|
||||
next: next,
|
||||
|
@ -60,7 +60,7 @@ func NewEntryPointMiddleware(ctx context.Context, next http.Handler, registry me
|
|||
|
||||
// NewRouterMiddleware creates a new metrics middleware for a Router.
|
||||
func NewRouterMiddleware(ctx context.Context, next http.Handler, registry metrics.Registry, routerName string, serviceName string) http.Handler {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, nameRouter, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, nameRouter, typeName).Debug().Msg("Creating middleware")
|
||||
|
||||
return &metricsMiddleware{
|
||||
next: next,
|
||||
|
@ -76,7 +76,7 @@ func NewRouterMiddleware(ctx context.Context, next http.Handler, registry metric
|
|||
|
||||
// NewServiceMiddleware creates a new metrics middleware for a Service.
|
||||
func NewServiceMiddleware(ctx context.Context, next http.Handler, registry metrics.Registry, serviceName string) http.Handler {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, nameService, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, nameService, typeName).Debug().Msg("Creating middleware")
|
||||
|
||||
return &metricsMiddleware{
|
||||
next: next,
|
||||
|
@ -129,10 +129,12 @@ func (m *metricsMiddleware) ServeHTTP(rw http.ResponseWriter, req *http.Request)
|
|||
|
||||
capt, err := capture.FromContext(ctx)
|
||||
if err != nil {
|
||||
with := log.Ctx(ctx).With()
|
||||
for i := 0; i < len(m.baseLabels); i += 2 {
|
||||
ctx = log.With(ctx, log.Str(m.baseLabels[i], m.baseLabels[i+1]))
|
||||
with = with.Str(m.baseLabels[i], m.baseLabels[i+1])
|
||||
}
|
||||
log.FromContext(ctx).WithError(err).Errorf("Could not get Capture")
|
||||
logger := with.Logger()
|
||||
logger.Error().Err(err).Msg("Could not get Capture")
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -223,7 +225,7 @@ func containsHeader(req *http.Request, name, value string) bool {
|
|||
//nolint:usestdlibvars
|
||||
func getMethod(r *http.Request) string {
|
||||
if !utf8.ValidString(r.Method) {
|
||||
log.WithoutContext().Warnf("Invalid HTTP method encoding: %s", r.Method)
|
||||
log.Warn().Msgf("Invalid HTTP method encoding: %s", r.Method)
|
||||
return "NON_UTF8_HTTP_METHOD"
|
||||
}
|
||||
|
||||
|
|
|
@ -3,10 +3,17 @@ package middlewares
|
|||
import (
|
||||
"context"
|
||||
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
)
|
||||
|
||||
// GetLoggerCtx creates a logger context with the middleware fields.
|
||||
func GetLoggerCtx(ctx context.Context, middleware, middlewareType string) context.Context {
|
||||
return log.With(ctx, log.Str(log.MiddlewareName, middleware), log.Str(log.MiddlewareType, middlewareType))
|
||||
// GetLogger creates a logger with the middleware fields.
|
||||
func GetLogger(ctx context.Context, middleware, middlewareType string) *zerolog.Logger {
|
||||
logger := log.Ctx(ctx).With().
|
||||
Str(logs.MiddlewareName, middleware).
|
||||
Str(logs.MiddlewareType, middlewareType).
|
||||
Logger()
|
||||
|
||||
return &logger
|
||||
}
|
||||
|
|
|
@ -12,8 +12,8 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
)
|
||||
|
@ -130,7 +130,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) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
|
||||
|
||||
return &passTLSClientCert{
|
||||
next: next,
|
||||
|
@ -145,14 +145,14 @@ func (p *passTLSClientCert) GetTracingInformation() (string, ext.SpanKindEnum) {
|
|||
}
|
||||
|
||||
func (p *passTLSClientCert) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
ctx := middlewares.GetLoggerCtx(req.Context(), p.name, typeName)
|
||||
logger := log.FromContext(ctx)
|
||||
logger := middlewares.GetLogger(req.Context(), p.name, typeName)
|
||||
ctx := logger.WithContext(req.Context())
|
||||
|
||||
if p.pem {
|
||||
if req.TLS != nil && len(req.TLS.PeerCertificates) > 0 {
|
||||
req.Header.Set(xForwardedTLSClientCert, getCertificates(ctx, req.TLS.PeerCertificates))
|
||||
} else {
|
||||
logger.Warn("Tried to extract a certificate on a request without mutual TLS")
|
||||
logger.Warn().Msg("Tried to extract a certificate on a request without mutual TLS")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -161,7 +161,7 @@ func (p *passTLSClientCert) ServeHTTP(rw http.ResponseWriter, req *http.Request)
|
|||
headerContent := p.getCertInfo(ctx, req.TLS.PeerCertificates)
|
||||
req.Header.Set(xForwardedTLSClientCertInfo, url.QueryEscape(headerContent))
|
||||
} else {
|
||||
logger.Warn("Tried to extract a certificate on a request without mutual TLS")
|
||||
logger.Warn().Msg("Tried to extract a certificate on a request without mutual TLS")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -318,7 +318,7 @@ func writePart(ctx context.Context, content io.StringWriter, entry, prefix strin
|
|||
if len(entry) > 0 {
|
||||
_, err := content.WriteString(fmt.Sprintf("%s=%s%s", prefix, entry, subFieldSeparator))
|
||||
if err != nil {
|
||||
log.FromContext(ctx).Error(err)
|
||||
log.Ctx(ctx).Error().Err(err).Send()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -347,7 +347,7 @@ func getCertificates(ctx context.Context, certs []*x509.Certificate) string {
|
|||
func extractCertificate(ctx context.Context, cert *x509.Certificate) string {
|
||||
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
|
||||
if certPEM == nil {
|
||||
log.FromContext(ctx).Error("Cannot extract the certificate content")
|
||||
log.Ctx(ctx).Error().Msg("Cannot extract the certificate content")
|
||||
return ""
|
||||
}
|
||||
|
||||
|
|
|
@ -10,11 +10,11 @@ import (
|
|||
|
||||
"github.com/mailgun/ttlmap"
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
"github.com/vulcand/oxy/utils"
|
||||
"github.com/vulcand/oxy/v2/utils"
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
|
@ -45,8 +45,10 @@ type rateLimiter struct {
|
|||
|
||||
// New returns a rate limiter middleware.
|
||||
func New(ctx context.Context, next http.Handler, config dynamic.RateLimit, name string) (http.Handler, error) {
|
||||
ctxLog := log.With(ctx, log.Str(log.MiddlewareName, name), log.Str(log.MiddlewareType, typeName))
|
||||
log.FromContext(ctxLog).Debug("Creating middleware")
|
||||
logger := middlewares.GetLogger(ctx, name, typeName)
|
||||
logger.Debug().Msg("Creating middleware")
|
||||
|
||||
ctxLog := logger.WithContext(ctx)
|
||||
|
||||
if config.SourceCriterion == nil ||
|
||||
config.SourceCriterion.IPStrategy == nil &&
|
||||
|
@ -122,19 +124,19 @@ func (rl *rateLimiter) GetTracingInformation() (string, ext.SpanKindEnum) {
|
|||
return rl.name, tracing.SpanKindNoneEnum
|
||||
}
|
||||
|
||||
func (rl *rateLimiter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := middlewares.GetLoggerCtx(r.Context(), rl.name, typeName)
|
||||
logger := log.FromContext(ctx)
|
||||
func (rl *rateLimiter) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
logger := middlewares.GetLogger(req.Context(), rl.name, typeName)
|
||||
ctx := logger.WithContext(req.Context())
|
||||
|
||||
source, amount, err := rl.sourceMatcher.Extract(r)
|
||||
source, amount, err := rl.sourceMatcher.Extract(req)
|
||||
if err != nil {
|
||||
logger.Errorf("could not extract source of request: %v", err)
|
||||
http.Error(w, "could not extract source of request", http.StatusInternalServerError)
|
||||
logger.Error().Err(err).Msg("Could not extract source of request")
|
||||
http.Error(rw, "could not extract source of request", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if amount != 1 {
|
||||
logger.Infof("ignoring token bucket amount > 1: %d", amount)
|
||||
logger.Info().Msgf("ignoring token bucket amount > 1: %d", amount)
|
||||
}
|
||||
|
||||
var bucket *rate.Limiter
|
||||
|
@ -148,8 +150,8 @@ func (rl *rateLimiter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||
// because we want to update the expiryTime everytime we get the source,
|
||||
// as the expiryTime is supposed to reflect the activity (or lack thereof) on that source.
|
||||
if err := rl.buckets.Set(source, bucket, rl.ttl); err != nil {
|
||||
logger.Errorf("could not insert/update bucket: %v", err)
|
||||
http.Error(w, "could not insert/update bucket", http.StatusInternalServerError)
|
||||
logger.Error().Err(err).Msg("Could not insert/update bucket")
|
||||
http.Error(rw, "could not insert/update bucket", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -159,19 +161,19 @@ func (rl *rateLimiter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||
// However, for now we take advantage of this behavior to provide the no-limit ratelimiter when config.Average is 0.
|
||||
res := bucket.Reserve()
|
||||
if !res.OK() {
|
||||
http.Error(w, "No bursty traffic allowed", http.StatusTooManyRequests)
|
||||
http.Error(rw, "No bursty traffic allowed", http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
|
||||
delay := res.Delay()
|
||||
if delay > rl.maxDelay {
|
||||
res.Cancel()
|
||||
rl.serveDelayError(ctx, w, delay)
|
||||
rl.serveDelayError(ctx, rw, delay)
|
||||
return
|
||||
}
|
||||
|
||||
time.Sleep(delay)
|
||||
rl.next.ServeHTTP(w, r)
|
||||
rl.next.ServeHTTP(rw, req)
|
||||
}
|
||||
|
||||
func (rl *rateLimiter) serveDelayError(ctx context.Context, w http.ResponseWriter, delay time.Duration) {
|
||||
|
@ -180,6 +182,6 @@ func (rl *rateLimiter) serveDelayError(ctx context.Context, w http.ResponseWrite
|
|||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
|
||||
if _, err := w.Write([]byte(http.StatusText(http.StatusTooManyRequests))); err != nil {
|
||||
log.FromContext(ctx).Errorf("could not serve 429: %v", err)
|
||||
log.Ctx(ctx).Error().Err(err).Msg("Could not serve 429")
|
||||
}
|
||||
}
|
||||
|
|
|
@ -14,7 +14,7 @@ import (
|
|||
ptypes "github.com/traefik/paerser/types"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/testhelpers"
|
||||
"github.com/vulcand/oxy/utils"
|
||||
"github.com/vulcand/oxy/v2/utils"
|
||||
)
|
||||
|
||||
func TestNewRateLimiter(t *testing.T) {
|
||||
|
|
|
@ -5,7 +5,6 @@ import (
|
|||
"net/http"
|
||||
"runtime"
|
||||
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
)
|
||||
|
||||
|
@ -20,7 +19,7 @@ type recovery struct {
|
|||
|
||||
// New creates recovery middleware.
|
||||
func New(ctx context.Context, next http.Handler) (http.Handler, error) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, middlewareName, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, middlewareName, typeName).Debug().Msg("Creating middleware")
|
||||
|
||||
return &recovery{
|
||||
next: next,
|
||||
|
@ -32,19 +31,19 @@ func (re *recovery) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
re.next.ServeHTTP(rw, req)
|
||||
}
|
||||
|
||||
func recoverFunc(rw http.ResponseWriter, r *http.Request) {
|
||||
func recoverFunc(rw http.ResponseWriter, req *http.Request) {
|
||||
if err := recover(); err != nil {
|
||||
logger := log.FromContext(middlewares.GetLoggerCtx(r.Context(), middlewareName, typeName))
|
||||
logger := middlewares.GetLogger(req.Context(), middlewareName, typeName)
|
||||
if !shouldLogPanic(err) {
|
||||
logger.Debugf("Request has been aborted [%s - %s]: %v", r.RemoteAddr, r.URL, err)
|
||||
logger.Debug().Msgf("Request has been aborted [%s - %s]: %v", req.RemoteAddr, req.URL, err)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Errorf("Recovered from panic in HTTP handler [%s - %s]: %+v", r.RemoteAddr, r.URL, err)
|
||||
logger.Error().Msgf("Recovered from panic in HTTP handler [%s - %s]: %+v", req.RemoteAddr, req.URL, err)
|
||||
const size = 64 << 10
|
||||
buf := make([]byte, size)
|
||||
buf = buf[:runtime.Stack(buf, false)]
|
||||
logger.Errorf("Stack: %s", buf)
|
||||
logger.Error().Msgf("Stack: %s", buf)
|
||||
|
||||
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
}
|
||||
|
|
|
@ -7,7 +7,7 @@ import (
|
|||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
"github.com/vulcand/oxy/utils"
|
||||
"github.com/vulcand/oxy/v2/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
|
@ -6,7 +6,6 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
)
|
||||
|
||||
|
@ -14,9 +13,9 @@ const typeRegexName = "RedirectRegex"
|
|||
|
||||
// NewRedirectRegex creates a redirect middleware.
|
||||
func NewRedirectRegex(ctx context.Context, next http.Handler, conf dynamic.RedirectRegex, name string) (http.Handler, error) {
|
||||
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)
|
||||
logger := middlewares.GetLogger(ctx, name, typeRegexName)
|
||||
logger.Debug().Msg("Creating middleware")
|
||||
logger.Debug().Msgf("Setting up redirection from %s to %s", conf.Regex, conf.Replacement)
|
||||
|
||||
return newRedirect(next, conf.Regex, conf.Replacement, conf.Permanent, rawURL, name)
|
||||
}
|
||||
|
|
|
@ -8,7 +8,6 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
)
|
||||
|
||||
|
@ -20,9 +19,9 @@ const (
|
|||
|
||||
// NewRedirectScheme creates a new RedirectScheme middleware.
|
||||
func NewRedirectScheme(ctx context.Context, next http.Handler, conf dynamic.RedirectScheme, name string) (http.Handler, error) {
|
||||
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeSchemeName))
|
||||
logger.Debug("Creating middleware")
|
||||
logger.Debugf("Setting up redirection to %s %s", conf.Scheme, conf.Port)
|
||||
logger := middlewares.GetLogger(ctx, name, typeSchemeName)
|
||||
logger.Debug().Msg("Creating middleware")
|
||||
logger.Debug().Msgf("Setting up redirection to %s %s", conf.Scheme, conf.Port)
|
||||
|
||||
if len(conf.Scheme) == 0 {
|
||||
return nil, errors.New("you must provide a target scheme")
|
||||
|
|
|
@ -7,7 +7,6 @@ import (
|
|||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
)
|
||||
|
@ -27,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) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
|
||||
|
||||
return &replacePath{
|
||||
next: next,
|
||||
|
@ -52,7 +51,7 @@ func (r *replacePath) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
var err error
|
||||
req.URL.Path, err = url.PathUnescape(req.URL.RawPath)
|
||||
if err != nil {
|
||||
log.FromContext(middlewares.GetLoggerCtx(context.Background(), r.name, typeName)).Error(err)
|
||||
middlewares.GetLogger(context.Background(), r.name, typeName).Error().Err(err).Send()
|
||||
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
|
|
@ -10,7 +10,6 @@ import (
|
|||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares/replacepath"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
|
@ -28,7 +27,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) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
|
||||
|
||||
exp, err := regexp.Compile(strings.TrimSpace(config.Regex))
|
||||
if err != nil {
|
||||
|
@ -63,7 +62,7 @@ func (rp *replacePathRegex) ServeHTTP(rw http.ResponseWriter, req *http.Request)
|
|||
var err error
|
||||
req.URL.Path, err = url.PathUnescape(req.URL.RawPath)
|
||||
if err != nil {
|
||||
log.FromContext(middlewares.GetLoggerCtx(context.Background(), rp.name, typeName)).Error(err)
|
||||
middlewares.GetLogger(context.Background(), rp.name, typeName).Error().Err(err).Send()
|
||||
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
|
|
@ -10,7 +10,7 @@ import (
|
|||
|
||||
"github.com/miekg/dns"
|
||||
"github.com/patrickmn/go-cache"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type cnameResolv struct {
|
||||
|
@ -46,12 +46,12 @@ func (hr *Resolver) CNAMEFlatten(ctx context.Context, host string) string {
|
|||
return value.(string)
|
||||
}
|
||||
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
cacheDuration := 0 * time.Second
|
||||
for depth := 0; depth < hr.ResolvDepth; depth++ {
|
||||
resolv, err := cnameResolve(ctx, request, hr.ResolvConfig)
|
||||
if err != nil {
|
||||
logger.Error(err)
|
||||
logger.Error().Err(err).Send()
|
||||
break
|
||||
}
|
||||
if resolv == nil {
|
||||
|
@ -66,7 +66,7 @@ func (hr *Resolver) CNAMEFlatten(ctx context.Context, host string) string {
|
|||
}
|
||||
|
||||
if err := hr.cache.Add(host, result, cacheDuration); err != nil {
|
||||
logger.Error(err)
|
||||
logger.Error().Err(err).Send()
|
||||
}
|
||||
|
||||
return result
|
||||
|
@ -88,7 +88,7 @@ func cnameResolve(ctx context.Context, host, resolvPath string) (*cnameResolv, e
|
|||
for _, server := range config.Servers {
|
||||
tempRecord, err := getRecord(client, m, server, config.Port)
|
||||
if err != nil {
|
||||
log.FromContext(ctx).Errorf("Failed to resolve host %s: %v", host, err)
|
||||
log.Ctx(ctx).Error().Err(err).Msgf("Failed to resolve host %s", host)
|
||||
continue
|
||||
}
|
||||
result = append(result, tempRecord)
|
||||
|
|
|
@ -14,7 +14,6 @@ import (
|
|||
"github.com/cenkalti/backoff/v4"
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
)
|
||||
|
@ -46,7 +45,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) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
|
||||
|
||||
if config.Attempts <= 0 {
|
||||
return nil, fmt.Errorf("incorrect (or empty) value for attempt (%d)", config.Attempts)
|
||||
|
@ -106,19 +105,19 @@ func (r *retry) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
return fmt.Errorf("attempt %d failed", attempts-1)
|
||||
}
|
||||
|
||||
logger := middlewares.GetLogger(req.Context(), r.name, typeName)
|
||||
|
||||
backOff := backoff.WithContext(r.newBackOff(), req.Context())
|
||||
|
||||
notify := func(err error, d time.Duration) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(req.Context(), r.name, typeName)).
|
||||
Debugf("New attempt %d for request: %v", attempts, req.URL)
|
||||
logger.Debug().Msgf("New attempt %d for request: %v", attempts, req.URL)
|
||||
|
||||
r.listener.Retried(req, attempts)
|
||||
}
|
||||
|
||||
err := backoff.RetryNotify(operation, backOff, notify)
|
||||
if err != nil {
|
||||
log.FromContext(middlewares.GetLoggerCtx(req.Context(), r.name, typeName)).
|
||||
Debugf("Final retry attempt failed: %v", err.Error())
|
||||
logger.Debug().Err(err).Msg("Final retry attempt failed")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -5,7 +5,7 @@ import (
|
|||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares/requestdecorator"
|
||||
traefiktls "github.com/traefik/traefik/v2/pkg/tls"
|
||||
)
|
||||
|
@ -36,11 +36,11 @@ func (s SNICheck) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
tlsOptionSNI := findTLSOptionName(s.tlsOptionsForHost, serverName, false)
|
||||
|
||||
if tlsOptionHeader != tlsOptionSNI {
|
||||
log.WithoutContext().
|
||||
WithField("host", host).
|
||||
WithField("req.Host", req.Host).
|
||||
WithField("req.TLS.ServerName", req.TLS.ServerName).
|
||||
Debugf("TLS options difference: SNI:%s, Header:%s", tlsOptionSNI, tlsOptionHeader)
|
||||
log.Debug().
|
||||
Str("host", host).
|
||||
Str("req.Host", req.Host).
|
||||
Str("req.TLS.ServerName", req.TLS.ServerName).
|
||||
Msgf("TLS options difference: SNI:%s, Header:%s", tlsOptionSNI, tlsOptionHeader)
|
||||
http.Error(rw, http.StatusText(http.StatusMisdirectedRequest), http.StatusMisdirectedRequest)
|
||||
return
|
||||
}
|
||||
|
|
|
@ -7,7 +7,6 @@ import (
|
|||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
)
|
||||
|
@ -28,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) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
|
||||
return &stripPrefix{
|
||||
prefixes: config.Prefixes,
|
||||
forceSlash: config.ForceSlash,
|
||||
|
|
|
@ -8,7 +8,6 @@ import (
|
|||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares/stripprefix"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
|
@ -27,7 +26,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) {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
|
||||
|
||||
stripPrefix := stripPrefixRegex{
|
||||
next: next,
|
||||
|
|
|
@ -7,7 +7,6 @@ import (
|
|||
"sync"
|
||||
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tcp"
|
||||
)
|
||||
|
@ -26,8 +25,8 @@ type inFlightConn struct {
|
|||
// New creates a max connections middleware.
|
||||
// The connections are identified and grouped by remote IP.
|
||||
func New(ctx context.Context, next tcp.Handler, config dynamic.TCPInFlightConn, name string) (tcp.Handler, error) {
|
||||
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
|
||||
logger.Debug("Creating middleware")
|
||||
logger := middlewares.GetLogger(ctx, name, typeName)
|
||||
logger.Debug().Msg("Creating middleware")
|
||||
|
||||
return &inFlightConn{
|
||||
name: name,
|
||||
|
@ -39,18 +38,17 @@ func New(ctx context.Context, next tcp.Handler, config dynamic.TCPInFlightConn,
|
|||
|
||||
// ServeTCP serves the given TCP connection.
|
||||
func (i *inFlightConn) ServeTCP(conn tcp.WriteCloser) {
|
||||
ctx := middlewares.GetLoggerCtx(context.Background(), i.name, typeName)
|
||||
logger := log.FromContext(ctx)
|
||||
logger := middlewares.GetLogger(context.Background(), i.name, typeName)
|
||||
|
||||
ip, _, err := net.SplitHostPort(conn.RemoteAddr().String())
|
||||
if err != nil {
|
||||
logger.Errorf("Cannot parse IP from remote addr: %v", err)
|
||||
logger.Error().Err(err).Msg("Cannot parse IP from remote addr")
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
|
||||
if err = i.increment(ip); err != nil {
|
||||
logger.Errorf("Connection rejected: %v", err)
|
||||
logger.Error().Err(err).Msg("Connection rejected")
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
|
|
|
@ -7,7 +7,6 @@ import (
|
|||
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/ip"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tcp"
|
||||
)
|
||||
|
@ -25,8 +24,8 @@ type ipAllowLister struct {
|
|||
|
||||
// New builds a new TCP IPAllowLister given a list of CIDR-Strings to allow.
|
||||
func New(ctx context.Context, next tcp.Handler, config dynamic.TCPIPAllowList, name string) (tcp.Handler, error) {
|
||||
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
|
||||
logger.Debug("Creating middleware")
|
||||
logger := middlewares.GetLogger(ctx, name, typeName)
|
||||
logger.Debug().Msg("Creating middleware")
|
||||
|
||||
if len(config.SourceRange) == 0 {
|
||||
return nil, errors.New("sourceRange is empty, IPAllowLister not created")
|
||||
|
@ -37,7 +36,7 @@ func New(ctx context.Context, next tcp.Handler, config dynamic.TCPIPAllowList, n
|
|||
return nil, fmt.Errorf("cannot parse CIDRs %s: %w", config.SourceRange, err)
|
||||
}
|
||||
|
||||
logger.Debugf("Setting up IPAllowLister with sourceRange: %s", config.SourceRange)
|
||||
logger.Debug().Msgf("Setting up IPAllowLister with sourceRange: %s", config.SourceRange)
|
||||
|
||||
return &ipAllowLister{
|
||||
allowLister: checker,
|
||||
|
@ -47,19 +46,18 @@ func New(ctx context.Context, next tcp.Handler, config dynamic.TCPIPAllowList, n
|
|||
}
|
||||
|
||||
func (al *ipAllowLister) ServeTCP(conn tcp.WriteCloser) {
|
||||
ctx := middlewares.GetLoggerCtx(context.Background(), al.name, typeName)
|
||||
logger := log.FromContext(ctx)
|
||||
logger := middlewares.GetLogger(context.Background(), al.name, typeName)
|
||||
|
||||
addr := conn.RemoteAddr().String()
|
||||
|
||||
err := al.allowLister.IsAuthorized(addr)
|
||||
if err != nil {
|
||||
logger.Errorf("Connection from %s rejected: %v", addr, err)
|
||||
logger.Error().Err(err).Msgf("Connection from %s rejected", addr)
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
|
||||
logger.Debugf("Connection from %s accepted", addr)
|
||||
logger.Debug().Msgf("Connection from %s accepted", addr)
|
||||
|
||||
al.next.ServeTCP(conn)
|
||||
}
|
||||
|
|
|
@ -7,7 +7,6 @@ import (
|
|||
"github.com/containous/alice"
|
||||
"github.com/opentracing/opentracing-go"
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
)
|
||||
|
@ -18,7 +17,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 {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, "tracing", entryPointTypeName)).Debug("Creating middleware")
|
||||
middlewares.GetLogger(ctx, "tracing", entryPointTypeName).Debug().Msg("Creating middleware")
|
||||
|
||||
return &entryPointMiddleware{
|
||||
entryPoint: entryPointName,
|
||||
|
@ -36,8 +35,8 @@ type entryPointMiddleware struct {
|
|||
func (e *entryPointMiddleware) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
spanCtx, err := e.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))
|
||||
if err != nil {
|
||||
log.FromContext(middlewares.GetLoggerCtx(req.Context(), "tracing", entryPointTypeName)).
|
||||
Debugf("Failed to extract the context: %v", err)
|
||||
middlewares.GetLogger(req.Context(), "tracing", entryPointTypeName).
|
||||
Debug().Err(err).Msg("Failed to extract the context")
|
||||
}
|
||||
|
||||
span, req, finish := e.StartSpanf(req, ext.SpanKindRPCServerEnum, "EntryPoint", []string{e.entryPoint, req.Host}, " ", ext.RPCServerOption(spanCtx))
|
||||
|
|
|
@ -5,7 +5,7 @@ import (
|
|||
"net/http"
|
||||
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
)
|
||||
|
@ -22,8 +22,8 @@ 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 {
|
||||
log.FromContext(middlewares.GetLoggerCtx(ctx, "tracing", forwarderTypeName)).
|
||||
Debugf("Added outgoing tracing middleware %s", service)
|
||||
middlewares.GetLogger(ctx, "tracing", forwarderTypeName).
|
||||
Debug().Str(logs.ServiceName, service).Msg("Added outgoing tracing middleware")
|
||||
|
||||
return &forwarderMiddleware{
|
||||
router: router,
|
||||
|
|
|
@ -6,7 +6,8 @@ import (
|
|||
|
||||
"github.com/containous/alice"
|
||||
"github.com/opentracing/opentracing-go/ext"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/tracing"
|
||||
)
|
||||
|
||||
|
@ -28,7 +29,7 @@ func Wrap(ctx context.Context, constructor alice.Constructor) alice.Constructor
|
|||
|
||||
if traceableHandler, ok := handler.(Traceable); ok {
|
||||
name, spanKind := traceableHandler.GetTracingInformation()
|
||||
log.FromContext(ctx).WithField(log.MiddlewareName, name).Debug("Adding tracing to middleware")
|
||||
log.Ctx(ctx).Debug().Str(logs.MiddlewareName, name).Msg("Adding tracing to middleware")
|
||||
return NewWrapper(handler, name, spanKind), nil
|
||||
}
|
||||
return handler, nil
|
||||
|
|
|
@ -7,8 +7,8 @@ import (
|
|||
"unicode/utf8"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/ip"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/middlewares/requestdecorator"
|
||||
"github.com/traefik/traefik/v2/pkg/rules"
|
||||
"github.com/vulcand/predicate"
|
||||
|
@ -143,7 +143,7 @@ func host(route *mux.Route, hosts ...string) error {
|
|||
if len(reqHost) == 0 {
|
||||
// If the request is an HTTP/1.0 request, then a Host may not be defined.
|
||||
if req.ProtoAtLeast(1, 1) {
|
||||
log.FromContext(req.Context()).Warnf("Could not retrieve CanonizedHost, rejecting %s", req.Host)
|
||||
log.Ctx(req.Context()).Warn().Msgf("Could not retrieve CanonizedHost, rejecting %s", req.Host)
|
||||
}
|
||||
|
||||
return false
|
||||
|
@ -155,7 +155,7 @@ func host(route *mux.Route, hosts ...string) error {
|
|||
if strings.EqualFold(reqHost, host) || strings.EqualFold(flatH, host) {
|
||||
return true
|
||||
}
|
||||
log.FromContext(req.Context()).Debugf("CNAMEFlattening: request %s which resolved to %s, is not matched to route %s", reqHost, flatH, host)
|
||||
log.Ctx(req.Context()).Debug().Msgf("CNAMEFlattening: request %s which resolved to %s, is not matched to route %s", reqHost, flatH, host)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
@ -197,7 +197,7 @@ func clientIP(route *mux.Route, clientIPs ...string) error {
|
|||
route.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool {
|
||||
ok, err := checker.Contains(strategy.GetIP(req))
|
||||
if err != nil {
|
||||
log.FromContext(req.Context()).Warnf("\"ClientIP\" matcher: could not match remote address : %w", err)
|
||||
log.Ctx(req.Context()).Warn().Err(err).Msg("\"ClientIP\" matcher: could not match remote address")
|
||||
return false
|
||||
}
|
||||
|
||||
|
|
|
@ -11,8 +11,8 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/go-acme/lego/v4/challenge/tlsalpn01"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/ip"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/rules"
|
||||
"github.com/traefik/traefik/v2/pkg/tcp"
|
||||
"github.com/traefik/traefik/v2/pkg/types"
|
||||
|
@ -246,7 +246,7 @@ type matchersTree struct {
|
|||
func (m *matchersTree) match(meta ConnData) bool {
|
||||
if m == nil {
|
||||
// This should never happen as it should have been detected during parsing.
|
||||
log.WithoutContext().Warnf("Rule matcher is nil")
|
||||
log.Warn().Msg("Rule matcher is nil")
|
||||
return false
|
||||
}
|
||||
|
||||
|
@ -261,7 +261,7 @@ func (m *matchersTree) match(meta ConnData) bool {
|
|||
return m.left.match(meta) && m.right.match(meta)
|
||||
default:
|
||||
// This should never happen as it should have been detected during parsing.
|
||||
log.WithoutContext().Warnf("Invalid rule operator %s", m.operator)
|
||||
log.Warn().Msgf("Invalid rule operator %s", m.operator)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
@ -279,7 +279,7 @@ func clientIP(tree *matchersTree, clientIPs ...string) error {
|
|||
|
||||
ok, err := checker.Contains(meta.remoteIP)
|
||||
if err != nil {
|
||||
log.WithoutContext().Warnf("\"ClientIP\" matcher: could not match remote address: %v", err)
|
||||
log.Warn().Err(err).Msg("\"ClientIP\" matcher: could not match remote address")
|
||||
return false
|
||||
}
|
||||
return ok
|
||||
|
|
|
@ -6,8 +6,9 @@ import (
|
|||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/yaegi/interp"
|
||||
"github.com/traefik/yaegi/stdlib"
|
||||
)
|
||||
|
@ -35,12 +36,13 @@ func NewBuilder(client *Client, plugins map[string]Descriptor, localPlugins map[
|
|||
return nil, fmt.Errorf("%s: failed to read manifest: %w", desc.ModuleName, err)
|
||||
}
|
||||
|
||||
logger := log.WithoutContext().WithFields(logrus.Fields{"plugin": "plugin-" + pName, "module": desc.ModuleName})
|
||||
logger := log.With().Str("plugin", "plugin-"+pName).Str("module", desc.ModuleName).Logger()
|
||||
|
||||
i := interp.New(interp.Options{
|
||||
GoPath: client.GoPath(),
|
||||
Env: os.Environ(),
|
||||
Stdout: logger.WriterLevel(logrus.DebugLevel),
|
||||
Stderr: logger.WriterLevel(logrus.ErrorLevel),
|
||||
Stdout: logs.NoLevel(logger, zerolog.DebugLevel),
|
||||
Stderr: logs.NoLevel(logger, zerolog.ErrorLevel),
|
||||
})
|
||||
|
||||
err = i.Use(stdlib.Symbols)
|
||||
|
@ -83,12 +85,13 @@ func NewBuilder(client *Client, plugins map[string]Descriptor, localPlugins map[
|
|||
return nil, fmt.Errorf("%s: failed to read manifest: %w", desc.ModuleName, err)
|
||||
}
|
||||
|
||||
logger := log.WithoutContext().WithFields(logrus.Fields{"plugin": "plugin-" + pName, "module": desc.ModuleName})
|
||||
logger := log.With().Str("plugin", "plugin-"+pName).Str("module", desc.ModuleName).Logger()
|
||||
|
||||
i := interp.New(interp.Options{
|
||||
GoPath: localGoPath,
|
||||
Env: os.Environ(),
|
||||
Stdout: logger.WriterLevel(logrus.DebugLevel),
|
||||
Stderr: logger.WriterLevel(logrus.ErrorLevel),
|
||||
Stdout: logs.NoLevel(logger, zerolog.DebugLevel),
|
||||
Stderr: logs.NoLevel(logger, zerolog.ErrorLevel),
|
||||
})
|
||||
|
||||
err = i.Use(stdlib.Symbols)
|
||||
|
|
|
@ -7,7 +7,7 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/hashicorp/go-multierror"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
const localGoPath = "./plugins-local/"
|
||||
|
@ -27,7 +27,7 @@ func SetupRemotePlugins(client *Client, plugins map[string]Descriptor) error {
|
|||
ctx := context.Background()
|
||||
|
||||
for pAlias, desc := range plugins {
|
||||
log.FromContext(ctx).Debugf("loading of plugin: %s: %s@%s", pAlias, desc.ModuleName, desc.Version)
|
||||
log.Ctx(ctx).Debug().Msgf("Loading of plugin: %s: %s@%s", pAlias, desc.ModuleName, desc.Version)
|
||||
|
||||
hash, err := client.Download(ctx, desc.ModuleName, desc.Version)
|
||||
if err != nil {
|
||||
|
|
|
@ -9,8 +9,9 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/provider"
|
||||
"github.com/traefik/traefik/v2/pkg/safe"
|
||||
"github.com/traefik/yaegi/interp"
|
||||
|
@ -158,21 +159,21 @@ func (p *Provider) Init() error {
|
|||
func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.WithoutContext().WithField(log.ProviderName, p.name).Errorf("panic inside the plugin %v", err)
|
||||
log.Error().Str(logs.ProviderName, p.name).Msgf("Panic inside the plugin %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
cfgChan := make(chan json.Marshaler)
|
||||
|
||||
pool.GoCtx(func(ctx context.Context) {
|
||||
logger := log.FromContext(log.With(ctx, log.Str(log.ProviderName, p.name)))
|
||||
logger := log.Ctx(ctx).With().Str(logs.ProviderName, p.name).Logger()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
err := p.pp.Stop()
|
||||
if err != nil {
|
||||
logger.Errorf("failed to stop the provider: %v", err)
|
||||
logger.Error().Err(err).Msg("Failed to stop the provider")
|
||||
}
|
||||
|
||||
return
|
||||
|
@ -180,14 +181,14 @@ func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.
|
|||
case cfgPg := <-cfgChan:
|
||||
marshalJSON, err := cfgPg.MarshalJSON()
|
||||
if err != nil {
|
||||
logger.Errorf("failed to marshal configuration: %v", err)
|
||||
logger.Error().Err(err).Msg("Failed to marshal configuration")
|
||||
continue
|
||||
}
|
||||
|
||||
cfg := &dynamic.Configuration{}
|
||||
err = json.Unmarshal(marshalJSON, cfg)
|
||||
if err != nil {
|
||||
logger.Errorf("failed to unmarshal configuration: %v", err)
|
||||
logger.Error().Err(err).Msg("Failed to unmarshal configuration")
|
||||
continue
|
||||
}
|
||||
|
||||
|
|
|
@ -9,7 +9,8 @@ import (
|
|||
|
||||
"github.com/go-acme/lego/v4/certcrypto"
|
||||
"github.com/go-acme/lego/v4/registration"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
)
|
||||
|
||||
// Account is used to store lets encrypt registration info.
|
||||
|
@ -56,8 +57,8 @@ func (a *Account) GetRegistration() *registration.Resource {
|
|||
func (a *Account) GetPrivateKey() crypto.PrivateKey {
|
||||
privateKey, err := x509.ParsePKCS1PrivateKey(a.PrivateKey)
|
||||
if err != nil {
|
||||
log.WithoutContext().WithField(log.ProviderName, "acme").
|
||||
Errorf("Cannot unmarshal private key %+v: %v", a.PrivateKey, err)
|
||||
log.Error().Str(logs.ProviderName, "acme").
|
||||
Err(err).Msgf("Cannot unmarshal private key %+v", a.PrivateKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -66,7 +67,7 @@ func (a *Account) GetPrivateKey() crypto.PrivateKey {
|
|||
|
||||
// GetKeyType used to determine which algo to used.
|
||||
func GetKeyType(ctx context.Context, value string) certcrypto.KeyType {
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
switch value {
|
||||
case "EC256":
|
||||
|
@ -80,10 +81,10 @@ func GetKeyType(ctx context.Context, value string) certcrypto.KeyType {
|
|||
case "RSA8192":
|
||||
return certcrypto.RSA8192
|
||||
case "":
|
||||
logger.Infof("The key type is empty. Use default key type %v.", certcrypto.RSA4096)
|
||||
logger.Info().Msgf("The key type is empty. Use default key type %v.", certcrypto.RSA4096)
|
||||
return certcrypto.RSA4096
|
||||
default:
|
||||
logger.Infof("Unable to determine the key type value %q: falling back on %v.", value, certcrypto.RSA4096)
|
||||
logger.Info().Msgf("Unable to determine the key type value %q: falling back on %v.", value, certcrypto.RSA4096)
|
||||
return certcrypto.RSA4096
|
||||
}
|
||||
}
|
||||
|
|
|
@ -13,7 +13,8 @@ import (
|
|||
|
||||
"github.com/cenkalti/backoff/v4"
|
||||
"github.com/go-acme/lego/v4/challenge/http01"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/safe"
|
||||
)
|
||||
|
||||
|
@ -70,12 +71,11 @@ func (c *ChallengeHTTP) Timeout() (timeout, interval time.Duration) {
|
|||
}
|
||||
|
||||
func (c *ChallengeHTTP) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
ctx := log.With(req.Context(), log.Str(log.ProviderName, "acme"))
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(req.Context()).With().Str(logs.ProviderName, "acme").Logger()
|
||||
|
||||
token, err := getPathParam(req.URL)
|
||||
if err != nil {
|
||||
logger.Errorf("Unable to get token: %v.", err)
|
||||
logger.Error().Err(err).Msg("Unable to get token")
|
||||
rw.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
@ -83,16 +83,16 @@ func (c *ChallengeHTTP) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
if token != "" {
|
||||
domain, _, err := net.SplitHostPort(req.Host)
|
||||
if err != nil {
|
||||
logger.Debugf("Unable to split host and port: %v. Fallback to request host.", err)
|
||||
logger.Debug().Err(err).Msg("Unable to split host and port. Fallback to request host.")
|
||||
domain = req.Host
|
||||
}
|
||||
|
||||
tokenValue := c.getTokenValue(ctx, token, domain)
|
||||
tokenValue := c.getTokenValue(logger.WithContext(req.Context()), token, domain)
|
||||
if len(tokenValue) > 0 {
|
||||
rw.WriteHeader(http.StatusOK)
|
||||
_, err = rw.Write(tokenValue)
|
||||
if err != nil {
|
||||
logger.Errorf("Unable to write token: %v", err)
|
||||
logger.Error().Err(err).Msg("Unable to write token")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
@ -102,8 +102,8 @@ func (c *ChallengeHTTP) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||
}
|
||||
|
||||
func (c *ChallengeHTTP) getTokenValue(ctx context.Context, token, domain string) []byte {
|
||||
logger := log.FromContext(ctx)
|
||||
logger.Debugf("Retrieving the ACME challenge for %s (token %q)...", domain, token)
|
||||
logger := log.Ctx(ctx)
|
||||
logger.Debug().Msgf("Retrieving the ACME challenge for %s (token %q)...", domain, token)
|
||||
|
||||
var result []byte
|
||||
|
||||
|
@ -125,14 +125,14 @@ func (c *ChallengeHTTP) getTokenValue(ctx context.Context, token, domain string)
|
|||
}
|
||||
|
||||
notify := func(err error, time time.Duration) {
|
||||
logger.Errorf("Error getting challenge for token retrying in %s", time)
|
||||
logger.Error().Msgf("Error getting challenge for token retrying in %s", time)
|
||||
}
|
||||
|
||||
ebo := backoff.NewExponentialBackOff()
|
||||
ebo.MaxElapsedTime = 60 * time.Second
|
||||
err := backoff.RetryNotify(safe.OperationWithRecover(operation), ebo, notify)
|
||||
if err != nil {
|
||||
logger.Errorf("Cannot retrieve the ACME challenge for %s (token %q): %v", domain, token, err)
|
||||
logger.Error().Err(err).Msgf("Cannot retrieve the ACME challenge for %s (token %q)", domain, token)
|
||||
return []byte{}
|
||||
}
|
||||
|
||||
|
|
|
@ -6,8 +6,9 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/challenge/tlsalpn01"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/safe"
|
||||
traefiktls "github.com/traefik/traefik/v2/pkg/tls"
|
||||
"github.com/traefik/traefik/v2/pkg/types"
|
||||
|
@ -36,8 +37,8 @@ func NewChallengeTLSALPN() *ChallengeTLSALPN {
|
|||
|
||||
// Present presents a challenge to obtain new ACME certificate.
|
||||
func (c *ChallengeTLSALPN) Present(domain, _, keyAuth string) error {
|
||||
logger := log.WithoutContext().WithField(log.ProviderName, providerNameALPN)
|
||||
logger.Debugf("TLS Challenge Present temp certificate for %s", domain)
|
||||
logger := log.With().Str(logs.ProviderName, providerNameALPN).Logger()
|
||||
logger.Debug().Msgf("TLS Challenge Present temp certificate for %s", domain)
|
||||
|
||||
certPEMBlock, keyPEMBlock, err := tlsalpn01.ChallengeBlocks(domain, keyAuth)
|
||||
if err != nil {
|
||||
|
@ -71,7 +72,7 @@ func (c *ChallengeTLSALPN) Present(domain, _, keyAuth string) error {
|
|||
|
||||
err = c.CleanUp(domain, "", keyAuth)
|
||||
if err != nil {
|
||||
logger.Errorf("Failed to clean up TLS challenge: %v", err)
|
||||
logger.Error().Err(err).Msg("Failed to clean up TLS challenge")
|
||||
}
|
||||
|
||||
return fmt.Errorf("timeout %s", t)
|
||||
|
@ -83,8 +84,8 @@ func (c *ChallengeTLSALPN) Present(domain, _, keyAuth string) error {
|
|||
|
||||
// CleanUp cleans the challenges when certificate is obtained.
|
||||
func (c *ChallengeTLSALPN) CleanUp(domain, _, keyAuth string) error {
|
||||
log.WithoutContext().WithField(log.ProviderName, providerNameALPN).
|
||||
Debugf("TLS Challenge CleanUp temp certificate for %s", domain)
|
||||
log.Debug().Str(logs.ProviderName, providerNameALPN).
|
||||
Msgf("TLS Challenge CleanUp temp certificate for %s", domain)
|
||||
|
||||
c.muCerts.Lock()
|
||||
delete(c.certs, keyAuth)
|
||||
|
|
|
@ -6,7 +6,8 @@ import (
|
|||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/safe"
|
||||
)
|
||||
|
||||
|
@ -52,7 +53,7 @@ func (s *LocalStore) get(resolverName string) (*StoredData, error) {
|
|||
}
|
||||
|
||||
if hasData {
|
||||
logger := log.WithoutContext().WithField(log.ProviderName, "acme")
|
||||
logger := log.With().Str(logs.ProviderName, "acme").Logger()
|
||||
|
||||
f, err := os.Open(s.filename)
|
||||
if err != nil {
|
||||
|
@ -76,7 +77,7 @@ func (s *LocalStore) get(resolverName string) (*StoredData, error) {
|
|||
for _, storedData := range s.storedData {
|
||||
for _, certificate := range storedData.Certificates {
|
||||
if len(certificate.Certificate.Certificate) == 0 || len(certificate.Key) == 0 {
|
||||
logger.Debugf("Deleting empty certificate %v for %v", certificate, certificate.Domain.ToStrArray())
|
||||
logger.Debug().Msgf("Deleting empty certificate %v for %v", certificate, certificate.Domain.ToStrArray())
|
||||
continue
|
||||
}
|
||||
certificates = append(certificates, certificate)
|
||||
|
@ -101,16 +102,16 @@ func (s *LocalStore) get(resolverName string) (*StoredData, error) {
|
|||
// listenSaveAction listens to a chan to store ACME data in json format into `LocalStore.filename`.
|
||||
func (s *LocalStore) listenSaveAction() {
|
||||
safe.Go(func() {
|
||||
logger := log.WithoutContext().WithField(log.ProviderName, "acme")
|
||||
logger := log.With().Str(logs.ProviderName, "acme").Logger()
|
||||
for object := range s.saveDataChan {
|
||||
data, err := json.MarshalIndent(object, "", " ")
|
||||
if err != nil {
|
||||
logger.Error(err)
|
||||
logger.Error().Err(err).Send()
|
||||
}
|
||||
|
||||
err = os.WriteFile(s.filename, data, 0o600)
|
||||
if err != nil {
|
||||
logger.Error(err)
|
||||
logger.Error().Err(err).Send()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
|
|
@ -19,9 +19,10 @@ import (
|
|||
"github.com/go-acme/lego/v4/lego"
|
||||
"github.com/go-acme/lego/v4/providers/dns"
|
||||
"github.com/go-acme/lego/v4/registration"
|
||||
"github.com/rs/zerolog/log"
|
||||
ptypes "github.com/traefik/paerser/types"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
httpmuxer "github.com/traefik/traefik/v2/pkg/muxer/http"
|
||||
tcpmuxer "github.com/traefik/traefik/v2/pkg/muxer/tcp"
|
||||
"github.com/traefik/traefik/v2/pkg/safe"
|
||||
|
@ -131,8 +132,7 @@ func (p *Provider) ListenConfiguration(config dynamic.Configuration) {
|
|||
|
||||
// Init for compatibility reason the BaseProvider implements an empty Init.
|
||||
func (p *Provider) Init() error {
|
||||
ctx := log.With(context.Background(), log.Str(log.ProviderName, p.ResolverName+".acme"))
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.With().Str(logs.ProviderName, p.ResolverName+".acme").Logger()
|
||||
|
||||
if len(p.Configuration.Storage) == 0 {
|
||||
return errors.New("unable to initialize ACME provider with no storage location for the certificates")
|
||||
|
@ -149,8 +149,8 @@ func (p *Provider) Init() error {
|
|||
}
|
||||
|
||||
// Reset Account if caServer changed, thus registration URI can be updated
|
||||
if p.account != nil && p.account.Registration != nil && !isAccountMatchingCaServer(ctx, p.account.Registration.URI, p.CAServer) {
|
||||
logger.Info("Account URI does not match the current CAServer. The account will be reset.")
|
||||
if p.account != nil && p.account.Registration != nil && !isAccountMatchingCaServer(logger.WithContext(context.Background()), p.account.Registration.URI, p.CAServer) {
|
||||
logger.Info().Msg("Account URI does not match the current CAServer. The account will be reset.")
|
||||
p.account = nil
|
||||
}
|
||||
|
||||
|
@ -169,17 +169,17 @@ func (p *Provider) Init() error {
|
|||
}
|
||||
|
||||
func isAccountMatchingCaServer(ctx context.Context, accountURI, serverURI string) bool {
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
aru, err := url.Parse(accountURI)
|
||||
if err != nil {
|
||||
logger.Infof("Unable to parse account.Registration URL: %v", err)
|
||||
logger.Info().Err(err).Str("registrationURL", accountURI).Msg("Unable to parse account.Registration URL")
|
||||
return false
|
||||
}
|
||||
|
||||
cau, err := url.Parse(serverURI)
|
||||
if err != nil {
|
||||
logger.Infof("Unable to parse CAServer URL: %v", err)
|
||||
logger.Info().Err(err).Str("caServerURL", serverURI).Msg("Unable to parse CAServer URL")
|
||||
return false
|
||||
}
|
||||
|
||||
|
@ -194,9 +194,9 @@ func (p *Provider) ThrottleDuration() time.Duration {
|
|||
// Provide allows the file provider to provide configurations to traefik
|
||||
// using the given Configuration channel.
|
||||
func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error {
|
||||
ctx := log.With(context.Background(),
|
||||
log.Str(log.ProviderName, p.ResolverName+".acme"),
|
||||
log.Str("ACME CA", p.Configuration.CAServer))
|
||||
logger := log.With().Str(logs.ProviderName, p.ResolverName+".acme").Str("acmeCA", p.Configuration.CAServer).
|
||||
Logger()
|
||||
ctx := logger.WithContext(context.Background())
|
||||
|
||||
p.pool = pool
|
||||
|
||||
|
@ -211,7 +211,7 @@ func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.
|
|||
p.configurationChan <- msg
|
||||
|
||||
renewPeriod, renewInterval := getCertificateRenewDurations(p.CertificatesDuration)
|
||||
log.FromContext(ctx).Debugf("Attempt to renew certificates %q before expiry and check every %q",
|
||||
logger.Debug().Msgf("Attempt to renew certificates %q before expiry and check every %q",
|
||||
renewPeriod, renewInterval)
|
||||
|
||||
p.renewCertificates(ctx, renewPeriod)
|
||||
|
@ -236,8 +236,9 @@ func (p *Provider) getClient() (*lego.Client, error) {
|
|||
p.clientMutex.Lock()
|
||||
defer p.clientMutex.Unlock()
|
||||
|
||||
ctx := log.With(context.Background(), log.Str(log.ProviderName, p.ResolverName+".acme"))
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.With().Str(logs.ProviderName, p.ResolverName+".acme").Logger()
|
||||
|
||||
ctx := logger.WithContext(context.Background())
|
||||
|
||||
if p.client != nil {
|
||||
return p.client, nil
|
||||
|
@ -248,13 +249,13 @@ func (p *Provider) getClient() (*lego.Client, error) {
|
|||
return nil, err
|
||||
}
|
||||
|
||||
logger.Debug("Building ACME client...")
|
||||
logger.Debug().Msg("Building ACME client...")
|
||||
|
||||
caServer := lego.LEDirectoryProduction
|
||||
if len(p.CAServer) > 0 {
|
||||
caServer = p.CAServer
|
||||
}
|
||||
logger.Debug(caServer)
|
||||
logger.Debug().Msg(caServer)
|
||||
|
||||
config := lego.NewConfig(account)
|
||||
config.CADirURL = caServer
|
||||
|
@ -290,7 +291,7 @@ func (p *Provider) getClient() (*lego.Client, error) {
|
|||
}
|
||||
|
||||
if p.DNSChallenge != nil && len(p.DNSChallenge.Provider) > 0 {
|
||||
logger.Debugf("Using DNS Challenge provider: %s", p.DNSChallenge.Provider)
|
||||
logger.Debug().Msgf("Using DNS Challenge provider: %s", p.DNSChallenge.Provider)
|
||||
|
||||
var provider challenge.Provider
|
||||
provider, err = dns.NewDNSChallengeProviderByName(p.DNSChallenge.Provider)
|
||||
|
@ -302,7 +303,7 @@ func (p *Provider) getClient() (*lego.Client, error) {
|
|||
dns01.CondOption(len(p.DNSChallenge.Resolvers) > 0, dns01.AddRecursiveNameservers(p.DNSChallenge.Resolvers)),
|
||||
dns01.WrapPreCheck(func(domain, fqdn, value string, check dns01.PreCheckFunc) (bool, error) {
|
||||
if p.DNSChallenge.DelayBeforeCheck > 0 {
|
||||
logger.Debugf("Delaying %d rather than validating DNS propagation now.", p.DNSChallenge.DelayBeforeCheck)
|
||||
logger.Debug().Msgf("Delaying %d rather than validating DNS propagation now.", p.DNSChallenge.DelayBeforeCheck)
|
||||
time.Sleep(time.Duration(p.DNSChallenge.DelayBeforeCheck))
|
||||
}
|
||||
|
||||
|
@ -319,7 +320,7 @@ func (p *Provider) getClient() (*lego.Client, error) {
|
|||
}
|
||||
|
||||
if p.HTTPChallenge != nil && len(p.HTTPChallenge.EntryPoint) > 0 {
|
||||
logger.Debug("Using HTTP Challenge provider.")
|
||||
logger.Debug().Msg("Using HTTP Challenge provider.")
|
||||
|
||||
err = client.Challenge.SetHTTP01Provider(p.HTTPChallengeProvider)
|
||||
if err != nil {
|
||||
|
@ -328,7 +329,7 @@ func (p *Provider) getClient() (*lego.Client, error) {
|
|||
}
|
||||
|
||||
if p.TLSChallenge != nil {
|
||||
logger.Debug("Using TLS Challenge provider.")
|
||||
logger.Debug().Msg("Using TLS Challenge provider.")
|
||||
|
||||
err = client.Challenge.SetTLSALPN01Provider(p.TLSChallengeProvider)
|
||||
if err != nil {
|
||||
|
@ -358,30 +359,30 @@ func (p *Provider) initAccount(ctx context.Context) (*Account, error) {
|
|||
}
|
||||
|
||||
func (p *Provider) register(ctx context.Context, client *lego.Client) (*registration.Resource, error) {
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
if p.EAB != nil {
|
||||
logger.Info("Register with external account binding...")
|
||||
logger.Info().Msg("Register with external account binding...")
|
||||
|
||||
eabOptions := registration.RegisterEABOptions{TermsOfServiceAgreed: true, Kid: p.EAB.Kid, HmacEncoded: p.EAB.HmacEncoded}
|
||||
|
||||
return client.Registration.RegisterWithExternalAccountBinding(eabOptions)
|
||||
}
|
||||
|
||||
logger.Info("Register...")
|
||||
logger.Info().Msg("Register...")
|
||||
|
||||
return client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
|
||||
}
|
||||
|
||||
func (p *Provider) resolveDomains(ctx context.Context, domains []string, tlsStore string) {
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
if len(domains) == 0 {
|
||||
logger.Debug("No domain parsed in provider ACME")
|
||||
logger.Debug().Msg("No domain parsed in provider ACME")
|
||||
return
|
||||
}
|
||||
|
||||
logger.Debugf("Trying to challenge certificate for domain %v found in HostSNI rule", domains)
|
||||
logger.Debug().Msgf("Trying to challenge certificate for domain %v found in HostSNI rule", domains)
|
||||
|
||||
var domain types.Domain
|
||||
if len(domains) > 0 {
|
||||
|
@ -393,20 +394,22 @@ func (p *Provider) resolveDomains(ctx context.Context, domains []string, tlsStor
|
|||
safe.Go(func() {
|
||||
dom, cert, err := p.resolveCertificate(ctx, domain, tlsStore)
|
||||
if err != nil {
|
||||
logger.Errorf("Unable to obtain ACME certificate for domains %q: %v", strings.Join(domains, ","), err)
|
||||
logger.Error().Err(err).Strs("domains", domains).Msg("Unable to obtain ACME certificate for domains")
|
||||
return
|
||||
}
|
||||
|
||||
err = p.addCertificateForDomain(dom, cert, tlsStore)
|
||||
if err != nil {
|
||||
logger.WithError(err).Error("Error adding certificate for domain")
|
||||
logger.Error().Err(err).Strs("domains", dom.ToStrArray()).Msg("Error adding certificate for domains")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Provider) watchNewDomains(ctx context.Context) {
|
||||
ctx = log.With(ctx, log.Str(log.ProviderName, p.ResolverName+".acme"))
|
||||
rootLogger := log.Ctx(ctx).With().Str(logs.ProviderName, p.ResolverName+".acme").Logger()
|
||||
ctx = rootLogger.WithContext(ctx)
|
||||
|
||||
p.pool.GoCtx(func(ctxPool context.Context) {
|
||||
for {
|
||||
select {
|
||||
|
@ -417,8 +420,8 @@ func (p *Provider) watchNewDomains(ctx context.Context) {
|
|||
continue
|
||||
}
|
||||
|
||||
ctxRouter := log.With(ctx, log.Str(log.RouterName, routerName), log.Str(log.Rule, route.Rule))
|
||||
logger := log.FromContext(ctxRouter)
|
||||
logger := rootLogger.With().Str(logs.RouterName, routerName).Str(logs.Rule, route.Rule).Logger()
|
||||
ctxRouter := logger.WithContext(ctx)
|
||||
|
||||
if len(route.TLS.Domains) > 0 {
|
||||
domains := deleteUnnecessaryDomains(ctxRouter, route.TLS.Domains)
|
||||
|
@ -427,20 +430,20 @@ func (p *Provider) watchNewDomains(ctx context.Context) {
|
|||
safe.Go(func() {
|
||||
dom, cert, err := p.resolveCertificate(ctx, domain, traefiktls.DefaultTLSStoreName)
|
||||
if err != nil {
|
||||
logger.WithError(err).Errorf("Unable to obtain ACME certificate for domains %q", strings.Join(domain.ToStrArray(), ","))
|
||||
logger.Error().Err(err).Strs("domains", domain.ToStrArray()).Msg("Unable to obtain ACME certificate for domains")
|
||||
return
|
||||
}
|
||||
|
||||
err = p.addCertificateForDomain(dom, cert, traefiktls.DefaultTLSStoreName)
|
||||
if err != nil {
|
||||
logger.WithError(err).Error("Error adding certificate for domain")
|
||||
logger.Error().Err(err).Strs("domains", dom.ToStrArray()).Msg("Error adding certificate for domains")
|
||||
}
|
||||
})
|
||||
}
|
||||
} else {
|
||||
domains, err := tcpmuxer.ParseHostSNI(route.Rule)
|
||||
if err != nil {
|
||||
logger.WithError(err).Errorf("Error parsing domains in provider ACME")
|
||||
logger.Error().Err(err).Msg("Error parsing domains in provider ACME")
|
||||
continue
|
||||
}
|
||||
p.resolveDomains(ctxRouter, domains, traefiktls.DefaultTLSStoreName)
|
||||
|
@ -454,8 +457,8 @@ func (p *Provider) watchNewDomains(ctx context.Context) {
|
|||
continue
|
||||
}
|
||||
|
||||
ctxRouter := log.With(ctx, log.Str(log.RouterName, routerName), log.Str(log.Rule, route.Rule))
|
||||
logger := log.FromContext(ctxRouter)
|
||||
logger := rootLogger.With().Str(logs.RouterName, routerName).Str(logs.Rule, route.Rule).Logger()
|
||||
ctxRouter := logger.WithContext(ctx)
|
||||
|
||||
if len(route.TLS.Domains) > 0 {
|
||||
domains := deleteUnnecessaryDomains(ctxRouter, route.TLS.Domains)
|
||||
|
@ -464,20 +467,20 @@ func (p *Provider) watchNewDomains(ctx context.Context) {
|
|||
safe.Go(func() {
|
||||
dom, cert, err := p.resolveCertificate(ctx, domain, traefiktls.DefaultTLSStoreName)
|
||||
if err != nil {
|
||||
logger.WithError(err).Errorf("Unable to obtain ACME certificate for domains %q", strings.Join(domain.ToStrArray(), ","))
|
||||
logger.Error().Err(err).Strs("domains", domain.ToStrArray()).Msg("Unable to obtain ACME certificate for domains")
|
||||
return
|
||||
}
|
||||
|
||||
err = p.addCertificateForDomain(dom, cert, traefiktls.DefaultTLSStoreName)
|
||||
if err != nil {
|
||||
logger.WithError(err).Error("Error adding certificate for domain")
|
||||
logger.Error().Err(err).Strs("domains", dom.ToStrArray()).Msg("Error adding certificate for domain")
|
||||
}
|
||||
})
|
||||
}
|
||||
} else {
|
||||
domains, err := httpmuxer.ParseDomains(route.Rule)
|
||||
if err != nil {
|
||||
logger.WithError(err).Errorf("Error parsing domains in provider ACME")
|
||||
logger.Error().Err(err).Msg("Error parsing domains in provider ACME")
|
||||
continue
|
||||
}
|
||||
p.resolveDomains(ctxRouter, domains, traefiktls.DefaultTLSStoreName)
|
||||
|
@ -490,11 +493,10 @@ func (p *Provider) watchNewDomains(ctx context.Context) {
|
|||
}
|
||||
|
||||
for tlsStoreName, tlsStore := range config.TLS.Stores {
|
||||
ctxTLSStore := log.With(ctx, log.Str(log.TLSStoreName, tlsStoreName))
|
||||
logger := log.FromContext(ctxTLSStore)
|
||||
logger := rootLogger.With().Str(logs.TLSStoreName, tlsStoreName).Logger()
|
||||
|
||||
if tlsStore.DefaultCertificate != nil && tlsStore.DefaultGeneratedCert != nil {
|
||||
logger.Warn("defaultCertificate and defaultGeneratedCert cannot be defined at the same time.")
|
||||
logger.Warn().Msg("defaultCertificate and defaultGeneratedCert cannot be defined at the same time.")
|
||||
}
|
||||
|
||||
// Gives precedence to the user defined default certificate.
|
||||
|
@ -503,7 +505,7 @@ func (p *Provider) watchNewDomains(ctx context.Context) {
|
|||
}
|
||||
|
||||
if tlsStore.DefaultGeneratedCert.Domain == nil || tlsStore.DefaultGeneratedCert.Resolver == "" {
|
||||
logger.Warn("default generated certificate domain or resolver is missing.")
|
||||
logger.Warn().Msg("default generated certificate domain or resolver is missing.")
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -513,18 +515,18 @@ func (p *Provider) watchNewDomains(ctx context.Context) {
|
|||
|
||||
validDomains, err := p.sanitizeDomains(ctx, *tlsStore.DefaultGeneratedCert.Domain)
|
||||
if err != nil {
|
||||
logger.WithError(err).Errorf("domains validation: %s", strings.Join(tlsStore.DefaultGeneratedCert.Domain.ToStrArray(), ","))
|
||||
logger.Error().Err(err).Strs("domains", tlsStore.DefaultGeneratedCert.Domain.ToStrArray()).Msg("domains validation")
|
||||
}
|
||||
|
||||
if p.certExists(validDomains) {
|
||||
logger.Debug("Default ACME certificate generation is not required.")
|
||||
logger.Debug().Msg("Default ACME certificate generation is not required.")
|
||||
continue
|
||||
}
|
||||
|
||||
safe.Go(func() {
|
||||
cert, err := p.resolveDefaultCertificate(ctx, validDomains)
|
||||
if err != nil {
|
||||
logger.WithError(err).Errorf("Unable to obtain ACME certificate for domain %q", strings.Join(validDomains, ","))
|
||||
logger.Error().Err(err).Strs("domains", validDomains).Msgf("Unable to obtain ACME certificate for domain")
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -537,7 +539,7 @@ func (p *Provider) watchNewDomains(ctx context.Context) {
|
|||
|
||||
err = p.addCertificateForDomain(domain, cert, traefiktls.DefaultTLSStoreName)
|
||||
if err != nil {
|
||||
logger.WithError(err).Error("Error adding certificate for domain")
|
||||
logger.Error().Err(err).Msg("Error adding certificate for domain")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
@ -549,7 +551,7 @@ func (p *Provider) watchNewDomains(ctx context.Context) {
|
|||
}
|
||||
|
||||
func (p *Provider) resolveDefaultCertificate(ctx context.Context, domains []string) (*certificate.Resource, error) {
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
p.resolvingDomainsMutex.Lock()
|
||||
|
||||
|
@ -571,7 +573,7 @@ func (p *Provider) resolveDefaultCertificate(ctx context.Context, domains []stri
|
|||
|
||||
defer p.removeResolvingDomains(append(domains, domainKey))
|
||||
|
||||
logger.Debugf("Loading ACME certificates %+v...", domains)
|
||||
logger.Debug().Msgf("Loading ACME certificates %+v...", domains)
|
||||
|
||||
client, err := p.getClient()
|
||||
if err != nil {
|
||||
|
@ -596,7 +598,7 @@ func (p *Provider) resolveDefaultCertificate(ctx context.Context, domains []stri
|
|||
return nil, fmt.Errorf("certificate for domains %v is empty: %v", domains, cert)
|
||||
}
|
||||
|
||||
logger.Debugf("Default certificate obtained for domains %+v", domains)
|
||||
logger.Debug().Msgf("Default certificate obtained for domains %+v", domains)
|
||||
|
||||
return cert, nil
|
||||
}
|
||||
|
@ -615,8 +617,8 @@ func (p *Provider) resolveCertificate(ctx context.Context, domain types.Domain,
|
|||
|
||||
defer p.removeResolvingDomains(uncheckedDomains)
|
||||
|
||||
logger := log.FromContext(ctx)
|
||||
logger.Debugf("Loading ACME certificates %+v...", uncheckedDomains)
|
||||
logger := log.Ctx(ctx)
|
||||
logger.Debug().Msgf("Loading ACME certificates %+v...", uncheckedDomains)
|
||||
|
||||
client, err := p.getClient()
|
||||
if err != nil {
|
||||
|
@ -641,7 +643,7 @@ func (p *Provider) resolveCertificate(ctx context.Context, domain types.Domain,
|
|||
return types.Domain{}, nil, fmt.Errorf("certificate for domains %v is empty: %v", uncheckedDomains, cert)
|
||||
}
|
||||
|
||||
logger.Debugf("Certificates obtained for domains %+v", uncheckedDomains)
|
||||
logger.Debug().Msgf("Certificates obtained for domains %+v", uncheckedDomains)
|
||||
|
||||
domain = types.Domain{Main: uncheckedDomains[0]}
|
||||
if len(uncheckedDomains) > 1 {
|
||||
|
@ -712,7 +714,7 @@ func getCertificateRenewDurations(certificatesDuration int) (time.Duration, time
|
|||
func deleteUnnecessaryDomains(ctx context.Context, domains []types.Domain) []types.Domain {
|
||||
var newDomains []types.Domain
|
||||
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
for idxDomainToCheck, domainToCheck := range domains {
|
||||
keepDomain := true
|
||||
|
@ -724,7 +726,7 @@ func deleteUnnecessaryDomains(ctx context.Context, domains []types.Domain) []typ
|
|||
|
||||
if reflect.DeepEqual(domain, domainToCheck) {
|
||||
if idxDomainToCheck > idxDomain {
|
||||
logger.Warnf("The domain %v is duplicated in the configuration but will be process by ACME provider only once.", domainToCheck)
|
||||
logger.Warn().Msgf("The domain %v is duplicated in the configuration but will be process by ACME provider only once.", domainToCheck)
|
||||
keepDomain = false
|
||||
}
|
||||
break
|
||||
|
@ -736,11 +738,11 @@ func deleteUnnecessaryDomains(ctx context.Context, domains []types.Domain) []typ
|
|||
for _, domainProcessed := range domainToCheck.ToStrArray() {
|
||||
if idxDomain < idxDomainToCheck && isDomainAlreadyChecked(domainProcessed, domain.ToStrArray()) {
|
||||
// The domain is duplicated in a CN
|
||||
logger.Warnf("Domain %q is duplicated in the configuration or validated by the domain %v. It will be processed once.", domainProcessed, domain)
|
||||
logger.Warn().Msgf("Domain %q is duplicated in the configuration or validated by the domain %v. It will be processed once.", domainProcessed, domain)
|
||||
continue
|
||||
} else if domain.Main != domainProcessed && strings.HasPrefix(domain.Main, "*") && isDomainAlreadyChecked(domainProcessed, []string{domain.Main}) {
|
||||
// Check if a wildcard can validate the domain
|
||||
logger.Warnf("Domain %q will not be processed by ACME provider because it is validated by the wildcard %q", domainProcessed, domain.Main)
|
||||
logger.Warn().Msgf("Domain %q will not be processed by ACME provider because it is validated by the wildcard %q", domainProcessed, domain.Main)
|
||||
continue
|
||||
}
|
||||
newDomainsToCheck = append(newDomainsToCheck, domainProcessed)
|
||||
|
@ -791,9 +793,9 @@ func (p *Provider) buildMessage() dynamic.Message {
|
|||
}
|
||||
|
||||
func (p *Provider) renewCertificates(ctx context.Context, renewPeriod time.Duration) {
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
logger.Info("Testing certificate renew...")
|
||||
logger.Info().Msg("Testing certificate renew...")
|
||||
|
||||
p.certificatesMu.RLock()
|
||||
|
||||
|
@ -811,11 +813,11 @@ func (p *Provider) renewCertificates(ctx context.Context, renewPeriod time.Durat
|
|||
for _, cert := range certificates {
|
||||
client, err := p.getClient()
|
||||
if err != nil {
|
||||
logger.WithError(err).Infof("Error renewing certificate from LE : %+v", cert.Domain)
|
||||
logger.Info().Err(err).Msgf("Error renewing certificate from LE : %+v", cert.Domain)
|
||||
continue
|
||||
}
|
||||
|
||||
logger.Infof("Renewing certificate from LE : %+v", cert.Domain)
|
||||
logger.Info().Msgf("Renewing certificate from LE : %+v", cert.Domain)
|
||||
|
||||
renewedCert, err := client.Certificate.Renew(certificate.Resource{
|
||||
Domain: cert.Domain.Main,
|
||||
|
@ -823,18 +825,18 @@ func (p *Provider) renewCertificates(ctx context.Context, renewPeriod time.Durat
|
|||
Certificate: cert.Certificate.Certificate,
|
||||
}, true, ocspMustStaple, p.PreferredChain)
|
||||
if err != nil {
|
||||
logger.WithError(err).Errorf("Error renewing certificate from LE: %v", cert.Domain)
|
||||
logger.Error().Err(err).Msgf("Error renewing certificate from LE: %v", cert.Domain)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(renewedCert.Certificate) == 0 || len(renewedCert.PrivateKey) == 0 {
|
||||
logger.Errorf("domains %v renew certificate with no value: %v", cert.Domain.ToStrArray(), cert)
|
||||
logger.Error().Msgf("domains %v renew certificate with no value: %v", cert.Domain.ToStrArray(), cert)
|
||||
continue
|
||||
}
|
||||
|
||||
err = p.addCertificateForDomain(cert.Domain, renewedCert, cert.Store)
|
||||
if err != nil {
|
||||
logger.WithError(err).Error("Error adding certificate for domain")
|
||||
logger.Error().Err(err).Msg("Error adding certificate for domain")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -842,7 +844,7 @@ func (p *Provider) renewCertificates(ctx context.Context, renewPeriod time.Durat
|
|||
// Get provided certificate which check a domains list (Main and SANs)
|
||||
// from static and dynamic provided certificates.
|
||||
func (p *Provider) getUncheckedDomains(ctx context.Context, domainsToCheck []string, tlsStore string) []string {
|
||||
log.FromContext(ctx).Debugf("Looking for provided certificate(s) to validate %q...", domainsToCheck)
|
||||
log.Ctx(ctx).Debug().Msgf("Looking for provided certificate(s) to validate %q...", domainsToCheck)
|
||||
|
||||
var allDomains []string
|
||||
store := p.tlsManager.GetStore(tlsStore)
|
||||
|
@ -884,21 +886,24 @@ func searchUncheckedDomains(ctx context.Context, domainsToCheck, existentDomains
|
|||
}
|
||||
}
|
||||
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
if len(uncheckedDomains) == 0 {
|
||||
logger.Debugf("No ACME certificate generation required for domains %q.", domainsToCheck)
|
||||
logger.Debug().Strs("domains", domainsToCheck).Msg("No ACME certificate generation required for domains")
|
||||
} else {
|
||||
logger.Debugf("Domains %q need ACME certificates generation for domains %q.", domainsToCheck, strings.Join(uncheckedDomains, ","))
|
||||
logger.Debug().Strs("domains", domainsToCheck).Msgf("Domains need ACME certificates generation for domains %q.", strings.Join(uncheckedDomains, ","))
|
||||
}
|
||||
return uncheckedDomains
|
||||
}
|
||||
|
||||
func getX509Certificate(ctx context.Context, cert *Certificate) (*x509.Certificate, error) {
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
tlsCert, err := tls.X509KeyPair(cert.Certificate, cert.Key)
|
||||
if err != nil {
|
||||
logger.WithError(err).Errorf("Failed to load TLS key pair from ACME certificate for domain %q (SAN : %q), certificate will be renewed", cert.Domain.Main, strings.Join(cert.Domain.SANs, ","))
|
||||
logger.Error().Err(err).
|
||||
Str("domain", cert.Domain.Main).
|
||||
Strs("SANs", cert.Domain.SANs).
|
||||
Msg("Failed to load TLS key pair from ACME certificate for domain, certificate will be renewed")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
@ -906,7 +911,10 @@ func getX509Certificate(ctx context.Context, cert *Certificate) (*x509.Certifica
|
|||
if crt == nil {
|
||||
crt, err = x509.ParseCertificate(tlsCert.Certificate[0])
|
||||
if err != nil {
|
||||
logger.WithError(err).Errorf("Failed to parse TLS key pair from ACME certificate for domain %q (SAN : %q), certificate will be renewed", cert.Domain.Main, strings.Join(cert.Domain.SANs, ","))
|
||||
logger.Error().Err(err).
|
||||
Str("domain", cert.Domain.Main).
|
||||
Strs("SANs", cert.Domain.SANs).
|
||||
Msg("Failed to parse TLS key pair from ACME certificate for domain, certificate will be renewed")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -935,7 +943,7 @@ func (p *Provider) sanitizeDomains(ctx context.Context, domain types.Domain) ([]
|
|||
canonicalDomain := types.CanonicalDomain(dom)
|
||||
cleanDomain := dns01.UnFqdn(canonicalDomain)
|
||||
if canonicalDomain != cleanDomain {
|
||||
log.FromContext(ctx).Warnf("FQDN detected, please remove the trailing dot: %s", canonicalDomain)
|
||||
log.Ctx(ctx).Warn().Msgf("FQDN detected, please remove the trailing dot: %s", canonicalDomain)
|
||||
}
|
||||
|
||||
cleanDomains = append(cleanDomains, cleanDomain)
|
||||
|
|
|
@ -4,9 +4,9 @@ import (
|
|||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/config/static"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/provider"
|
||||
"github.com/traefik/traefik/v2/pkg/provider/file"
|
||||
"github.com/traefik/traefik/v2/pkg/provider/traefik"
|
||||
|
@ -148,7 +148,7 @@ func NewProviderAggregator(conf static.Providers) ProviderAggregator {
|
|||
func (p *ProviderAggregator) quietAddProvider(provider provider.Provider) {
|
||||
err := p.AddProvider(provider)
|
||||
if err != nil {
|
||||
log.WithoutContext().Errorf("Error while initializing provider %T: %v", provider, err)
|
||||
log.Error().Err(err).Msgf("Error while initializing provider %T", provider)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -201,14 +201,14 @@ func (p ProviderAggregator) Provide(configurationChan chan<- dynamic.Message, po
|
|||
func (p ProviderAggregator) launchProvider(configurationChan chan<- dynamic.Message, pool *safe.Pool, prd provider.Provider) {
|
||||
jsonConf, err := redactor.RemoveCredentials(prd)
|
||||
if err != nil {
|
||||
log.WithoutContext().Debugf("Cannot marshal the provider configuration %T: %v", prd, err)
|
||||
log.Debug().Err(err).Msgf("Cannot marshal the provider configuration %T", prd)
|
||||
}
|
||||
|
||||
log.WithoutContext().Infof("Starting provider %T", prd)
|
||||
log.WithoutContext().Debugf("%T provider configuration: %s", prd, jsonConf)
|
||||
log.Info().Msgf("Starting provider %T", prd)
|
||||
log.Debug().RawJSON("config", []byte(jsonConf)).Msgf("%T provider configuration", prd)
|
||||
|
||||
if err := maybeThrottledProvide(prd, p.providersThrottleDuration)(configurationChan, pool); err != nil {
|
||||
log.WithoutContext().Errorf("Cannot start the provider %T: %v", prd, err)
|
||||
log.Error().Err(err).Msgf("Cannot start the provider %T", prd)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,13 +10,14 @@ import (
|
|||
"unicode"
|
||||
|
||||
"github.com/Masterminds/sprig/v3"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
)
|
||||
|
||||
// Merge Merges multiple configurations.
|
||||
func Merge(ctx context.Context, configurations map[string]*dynamic.Configuration) *dynamic.Configuration {
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
configuration := &dynamic.Configuration{
|
||||
HTTP: &dynamic.HTTPConfiguration{
|
||||
|
@ -136,56 +137,56 @@ func Merge(ctx context.Context, configurations map[string]*dynamic.Configuration
|
|||
}
|
||||
|
||||
for serviceName := range servicesToDelete {
|
||||
logger.WithField(log.ServiceName, serviceName).
|
||||
Errorf("Service defined multiple times with different configurations in %v", services[serviceName])
|
||||
logger.Error().Str(logs.ServiceName, serviceName).
|
||||
Msgf("Service defined multiple times with different configurations in %v", services[serviceName])
|
||||
delete(configuration.HTTP.Services, serviceName)
|
||||
}
|
||||
|
||||
for routerName := range routersToDelete {
|
||||
logger.WithField(log.RouterName, routerName).
|
||||
Errorf("Router defined multiple times with different configurations in %v", routers[routerName])
|
||||
logger.Error().Str(logs.RouterName, routerName).
|
||||
Msgf("Router defined multiple times with different configurations in %v", routers[routerName])
|
||||
delete(configuration.HTTP.Routers, routerName)
|
||||
}
|
||||
|
||||
for transportName := range transportsToDelete {
|
||||
logger.WithField(log.ServersTransportName, transportName).
|
||||
Errorf("ServersTransport defined multiple times with different configurations in %v", transports[transportName])
|
||||
logger.Error().Str(logs.ServersTransportName, transportName).
|
||||
Msgf("ServersTransport defined multiple times with different configurations in %v", transports[transportName])
|
||||
delete(configuration.HTTP.ServersTransports, transportName)
|
||||
}
|
||||
|
||||
for serviceName := range servicesTCPToDelete {
|
||||
logger.WithField(log.ServiceName, serviceName).
|
||||
Errorf("Service TCP defined multiple times with different configurations in %v", servicesTCP[serviceName])
|
||||
logger.Error().Str(logs.ServiceName, serviceName).
|
||||
Msgf("Service TCP defined multiple times with different configurations in %v", servicesTCP[serviceName])
|
||||
delete(configuration.TCP.Services, serviceName)
|
||||
}
|
||||
|
||||
for routerName := range routersTCPToDelete {
|
||||
logger.WithField(log.RouterName, routerName).
|
||||
Errorf("Router TCP defined multiple times with different configurations in %v", routersTCP[routerName])
|
||||
logger.Error().Str(logs.RouterName, routerName).
|
||||
Msgf("Router TCP defined multiple times with different configurations in %v", routersTCP[routerName])
|
||||
delete(configuration.TCP.Routers, routerName)
|
||||
}
|
||||
|
||||
for serviceName := range servicesUDPToDelete {
|
||||
logger.WithField(log.ServiceName, serviceName).
|
||||
Errorf("UDP service defined multiple times with different configurations in %v", servicesUDP[serviceName])
|
||||
logger.Error().Str(logs.ServiceName, serviceName).
|
||||
Msgf("UDP service defined multiple times with different configurations in %v", servicesUDP[serviceName])
|
||||
delete(configuration.UDP.Services, serviceName)
|
||||
}
|
||||
|
||||
for routerName := range routersUDPToDelete {
|
||||
logger.WithField(log.RouterName, routerName).
|
||||
Errorf("UDP router defined multiple times with different configurations in %v", routersUDP[routerName])
|
||||
logger.Error().Str(logs.RouterName, routerName).
|
||||
Msgf("UDP router defined multiple times with different configurations in %v", routersUDP[routerName])
|
||||
delete(configuration.UDP.Routers, routerName)
|
||||
}
|
||||
|
||||
for middlewareName := range middlewaresToDelete {
|
||||
logger.WithField(log.MiddlewareName, middlewareName).
|
||||
Errorf("Middleware defined multiple times with different configurations in %v", middlewares[middlewareName])
|
||||
logger.Error().Str(logs.MiddlewareName, middlewareName).
|
||||
Msgf("Middleware defined multiple times with different configurations in %v", middlewares[middlewareName])
|
||||
delete(configuration.HTTP.Middlewares, middlewareName)
|
||||
}
|
||||
|
||||
for middlewareName := range middlewaresTCPToDelete {
|
||||
logger.WithField(log.MiddlewareName, middlewareName).
|
||||
Errorf("TCP Middleware defined multiple times with different configurations in %v", middlewaresTCP[middlewareName])
|
||||
logger.Error().Str(logs.MiddlewareName, middlewareName).
|
||||
Msgf("TCP Middleware defined multiple times with different configurations in %v", middlewaresTCP[middlewareName])
|
||||
delete(configuration.TCP.Middlewares, middlewareName)
|
||||
}
|
||||
|
||||
|
@ -342,18 +343,19 @@ func MakeDefaultRuleTemplate(defaultRule string, funcMap template.FuncMap) (*tem
|
|||
// BuildTCPRouterConfiguration Builds a router configuration.
|
||||
func BuildTCPRouterConfiguration(ctx context.Context, configuration *dynamic.TCPConfiguration) {
|
||||
for routerName, router := range configuration.Routers {
|
||||
loggerRouter := log.FromContext(ctx).WithField(log.RouterName, routerName)
|
||||
loggerRouter := log.Ctx(ctx).With().Str(logs.RouterName, routerName).Logger()
|
||||
|
||||
if len(router.Rule) == 0 {
|
||||
delete(configuration.Routers, routerName)
|
||||
loggerRouter.Errorf("Empty rule")
|
||||
loggerRouter.Error().Msg("Empty rule")
|
||||
continue
|
||||
}
|
||||
|
||||
if len(router.Service) == 0 {
|
||||
if len(configuration.Services) > 1 {
|
||||
delete(configuration.Routers, routerName)
|
||||
loggerRouter.
|
||||
Error("Could not define the service name for the router: too many services")
|
||||
loggerRouter.Error().
|
||||
Msg("Could not define the service name for the router: too many services")
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -367,7 +369,8 @@ func BuildTCPRouterConfiguration(ctx context.Context, configuration *dynamic.TCP
|
|||
// BuildUDPRouterConfiguration Builds a router configuration.
|
||||
func BuildUDPRouterConfiguration(ctx context.Context, configuration *dynamic.UDPConfiguration) {
|
||||
for routerName, router := range configuration.Routers {
|
||||
loggerRouter := log.FromContext(ctx).WithField(log.RouterName, routerName)
|
||||
loggerRouter := log.Ctx(ctx).With().Str(logs.RouterName, routerName).Logger()
|
||||
|
||||
if len(router.Service) > 0 {
|
||||
continue
|
||||
}
|
||||
|
@ -375,7 +378,7 @@ func BuildUDPRouterConfiguration(ctx context.Context, configuration *dynamic.UDP
|
|||
if len(configuration.Services) > 1 {
|
||||
delete(configuration.Routers, routerName)
|
||||
loggerRouter.
|
||||
Error("Could not define the service name for the router: too many services")
|
||||
Error().Msg("Could not define the service name for the router: too many services")
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -390,7 +393,7 @@ func BuildUDPRouterConfiguration(ctx context.Context, configuration *dynamic.UDP
|
|||
func BuildRouterConfiguration(ctx context.Context, configuration *dynamic.HTTPConfiguration, defaultRouterName string, defaultRuleTpl *template.Template, model interface{}) {
|
||||
if len(configuration.Routers) == 0 {
|
||||
if len(configuration.Services) > 1 {
|
||||
log.FromContext(ctx).Info("Could not create a router for the container: too many services")
|
||||
log.Ctx(ctx).Info().Msg("Could not create a router for the container: too many services")
|
||||
} else {
|
||||
configuration.Routers = make(map[string]*dynamic.Router)
|
||||
configuration.Routers[defaultRouterName] = &dynamic.Router{}
|
||||
|
@ -398,18 +401,19 @@ func BuildRouterConfiguration(ctx context.Context, configuration *dynamic.HTTPCo
|
|||
}
|
||||
|
||||
for routerName, router := range configuration.Routers {
|
||||
loggerRouter := log.FromContext(ctx).WithField(log.RouterName, routerName)
|
||||
loggerRouter := log.Ctx(ctx).With().Str(logs.RouterName, routerName).Logger()
|
||||
|
||||
if len(router.Rule) == 0 {
|
||||
writer := &bytes.Buffer{}
|
||||
if err := defaultRuleTpl.Execute(writer, model); err != nil {
|
||||
loggerRouter.Errorf("Error while parsing default rule: %v", err)
|
||||
loggerRouter.Error().Err(err).Msg("Error while parsing default rule")
|
||||
delete(configuration.Routers, routerName)
|
||||
continue
|
||||
}
|
||||
|
||||
router.Rule = writer.String()
|
||||
if len(router.Rule) == 0 {
|
||||
loggerRouter.Error("Undefined rule")
|
||||
loggerRouter.Error().Msg("Undefined rule")
|
||||
delete(configuration.Routers, routerName)
|
||||
continue
|
||||
}
|
||||
|
@ -418,8 +422,8 @@ func BuildRouterConfiguration(ctx context.Context, configuration *dynamic.HTTPCo
|
|||
if len(router.Service) == 0 {
|
||||
if len(configuration.Services) > 1 {
|
||||
delete(configuration.Routers, routerName)
|
||||
loggerRouter.
|
||||
Error("Could not define the service name for the router: too many services")
|
||||
loggerRouter.Error().
|
||||
Msg("Could not define the service name for the router: too many services")
|
||||
continue
|
||||
}
|
||||
|
||||
|
|
|
@ -10,9 +10,10 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/hashicorp/consul/api"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/config/label"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/provider"
|
||||
"github.com/traefik/traefik/v2/pkg/provider/constraints"
|
||||
)
|
||||
|
@ -22,17 +23,17 @@ func (p *Provider) buildConfiguration(ctx context.Context, items []itemData, cer
|
|||
|
||||
for _, item := range items {
|
||||
svcName := provider.Normalize(item.Node + "-" + item.Name + "-" + item.ID)
|
||||
ctxSvc := log.With(ctx, log.Str(log.ServiceName, svcName))
|
||||
|
||||
logger := log.Ctx(ctx).With().Str(logs.ServiceName, svcName).Logger()
|
||||
ctxSvc := logger.WithContext(ctx)
|
||||
|
||||
if !p.keepContainer(ctxSvc, item) {
|
||||
continue
|
||||
}
|
||||
|
||||
logger := log.FromContext(ctxSvc)
|
||||
|
||||
confFromLabel, err := label.DecodeConfiguration(item.Labels)
|
||||
if err != nil {
|
||||
logger.Error(err)
|
||||
logger.Error().Err(err).Send()
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -41,7 +42,7 @@ func (p *Provider) buildConfiguration(ctx context.Context, items []itemData, cer
|
|||
tcpOrUDP = true
|
||||
|
||||
if err := p.buildTCPServiceConfiguration(item, confFromLabel.TCP); err != nil {
|
||||
logger.Error(err)
|
||||
logger.Error().Err(err).Send()
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -52,7 +53,7 @@ func (p *Provider) buildConfiguration(ctx context.Context, items []itemData, cer
|
|||
tcpOrUDP = true
|
||||
|
||||
if err := p.buildUDPServiceConfiguration(item, confFromLabel.UDP); err != nil {
|
||||
logger.Error(err)
|
||||
logger.Error().Err(err).Send()
|
||||
continue
|
||||
}
|
||||
provider.BuildUDPRouterConfiguration(ctxSvc, confFromLabel.UDP)
|
||||
|
@ -77,7 +78,7 @@ func (p *Provider) buildConfiguration(ctx context.Context, items []itemData, cer
|
|||
}
|
||||
|
||||
if err = p.buildServiceConfiguration(item, confFromLabel.HTTP); err != nil {
|
||||
logger.Error(err)
|
||||
logger.Error().Err(err).Send()
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -98,30 +99,30 @@ func (p *Provider) buildConfiguration(ctx context.Context, items []itemData, cer
|
|||
}
|
||||
|
||||
func (p *Provider) keepContainer(ctx context.Context, item itemData) bool {
|
||||
logger := log.FromContext(ctx)
|
||||
logger := log.Ctx(ctx)
|
||||
|
||||
if !item.ExtraConf.Enable {
|
||||
logger.Debug("Filtering disabled item")
|
||||
logger.Debug().Msg("Filtering disabled item")
|
||||
return false
|
||||
}
|
||||
|
||||
if !p.ConnectAware && item.ExtraConf.ConsulCatalog.Connect {
|
||||
logger.Debugf("Filtering out Connect aware item, Connect support is not enabled")
|
||||
logger.Debug().Msg("Filtering out Connect aware item, Connect support is not enabled")
|
||||
return false
|
||||
}
|
||||
|
||||
matches, err := constraints.MatchTags(item.Tags, p.Constraints)
|
||||
if err != nil {
|
||||
logger.Errorf("Error matching constraint expressions: %v", err)
|
||||
logger.Error().Err(err).Msg("Error matching constraint expressions")
|
||||
return false
|
||||
}
|
||||
if !matches {
|
||||
logger.Debugf("Container pruned by constraint expressions: %q", p.Constraints)
|
||||
logger.Debug().Msgf("Container pruned by constraint expressions: %q", p.Constraints)
|
||||
return false
|
||||
}
|
||||
|
||||
if item.Status != api.HealthPassing && item.Status != api.HealthWarning {
|
||||
logger.Debug("Filtering unhealthy or starting item")
|
||||
logger.Debug().Msg("Filtering unhealthy or starting item")
|
||||
return false
|
||||
}
|
||||
|
||||
|
|
|
@ -11,11 +11,12 @@ import (
|
|||
"github.com/hashicorp/consul/api"
|
||||
"github.com/hashicorp/consul/api/watch"
|
||||
"github.com/hashicorp/go-hclog"
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
ptypes "github.com/traefik/paerser/types"
|
||||
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
||||
"github.com/traefik/traefik/v2/pkg/job"
|
||||
"github.com/traefik/traefik/v2/pkg/log"
|
||||
"github.com/traefik/traefik/v2/pkg/logs"
|
||||
"github.com/traefik/traefik/v2/pkg/provider"
|
||||
"github.com/traefik/traefik/v2/pkg/provider/constraints"
|
||||
"github.com/traefik/traefik/v2/pkg/safe"
|
||||
|
@ -58,7 +59,7 @@ func (p *ProviderBuilder) BuildProviders() []*Provider {
|
|||
// We can warn about that, because we've already made sure before that
|
||||
// Namespace and Namespaces are mutually exclusive.
|
||||
if p.Namespace != "" {
|
||||
log.WithoutContext().Warnf("Namespace option is deprecated, please use the Namespaces option instead.")
|
||||
log.Warn().Msg("Namespace option is deprecated, please use the Namespaces option instead.")
|
||||
}
|
||||
|
||||
if len(p.Namespaces) == 0 {
|
||||
|
@ -166,8 +167,8 @@ func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.
|
|||
}
|
||||
|
||||
pool.GoCtx(func(routineCtx context.Context) {
|
||||
ctxLog := log.With(routineCtx, log.Str(log.ProviderName, p.name))
|
||||
logger := log.FromContext(ctxLog)
|
||||
logger := log.Ctx(routineCtx).With().Str(logs.ProviderName, p.name).Logger()
|
||||
ctxLog := logger.WithContext(routineCtx)
|
||||
|
||||
operation := func() error {
|
||||
ctx, cancel := context.WithCancel(ctxLog)
|
||||
|
@ -194,7 +195,7 @@ func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.
|
|||
// that gets resolved before the certificates are available
|
||||
// will cause an error condition.
|
||||
if p.ConnectAware && !certInfo.isReady() {
|
||||
logger.Infof("Waiting for Connect certificate before building first configuration")
|
||||
logger.Info().Msg("Waiting for Connect certificate before building first configuration")
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
|
@ -242,12 +243,12 @@ func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.
|
|||
}
|
||||
|
||||
notify := func(err error, time time.Duration) {
|
||||
logger.Errorf("Provider connection error %+v, retrying in %s", err, time)
|
||||
logger.Error().Err(err).Msgf("Provider connection error, retrying in %s", time)
|
||||
}
|
||||
|
||||
err := backoff.RetryNotify(safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctxLog), notify)
|
||||
if err != nil {
|
||||
logger.Errorf("Cannot connect to consul catalog server %+v", err)
|
||||
logger.Error().Err(err).Msg("Cannot connect to consul catalog server")
|
||||
}
|
||||
})
|
||||
|
||||
|
@ -281,32 +282,32 @@ func (p *Provider) getConsulServicesData(ctx context.Context) ([]itemData, error
|
|||
|
||||
var data []itemData
|
||||
for name, tags := range serviceNames {
|
||||
logger := log.FromContext(log.With(ctx, log.Str("serviceName", name)))
|
||||
logger := log.Ctx(ctx).With().Str("serviceName", name).Logger()
|
||||
|
||||
extraConf, err := p.getExtraConf(tagsToNeutralLabels(tags, p.Prefix))
|
||||
if err != nil {
|
||||
logger.Errorf("Skip service: %v", err)
|
||||
logger.Error().Err(err).Msg("Skip service")
|
||||
continue
|
||||
}
|
||||
|
||||
if !extraConf.Enable {
|
||||
logger.Debug("Filtering disabled item")
|
||||
logger.Debug().Msg("Filtering disabled item")
|
||||
continue
|
||||
}
|
||||
|
||||
matches, err := constraints.MatchTags(tags, p.Constraints)
|
||||
if err != nil {
|
||||
logger.Errorf("Error matching constraint expressions: %v", err)
|
||||
logger.Error().Err(err).Msg("Error matching constraint expressions")
|
||||
continue
|
||||
}
|
||||
|
||||
if !matches {
|
||||
logger.Debugf("Container pruned by constraint expressions: %q", p.Constraints)
|
||||
logger.Debug().Msgf("Container pruned by constraint expressions: %q", p.Constraints)
|
||||
continue
|
||||
}
|
||||
|
||||
if !p.ConnectAware && extraConf.ConsulCatalog.Connect {
|
||||
logger.Debugf("Filtering out Connect aware item, Connect support is not enabled")
|
||||
logger.Debug().Msg("Filtering out Connect aware item, Connect support is not enabled")
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -346,7 +347,7 @@ func (p *Provider) getConsulServicesData(ctx context.Context) ([]itemData, error
|
|||
|
||||
extraConf, err := p.getExtraConf(item.Labels)
|
||||
if err != nil {
|
||||
log.FromContext(ctx).Errorf("Skip item %s: %v", item.Name, err)
|
||||
log.Ctx(ctx).Error().Err(err).Msgf("Skip item %s", item.Name)
|
||||
continue
|
||||
}
|
||||
item.ExtraConf = extraConf
|
||||
|
@ -424,8 +425,9 @@ func (p *Provider) watchServices(ctx context.Context) error {
|
|||
|
||||
logger := hclog.New(&hclog.LoggerOptions{
|
||||
Name: "consulcatalog",
|
||||
Level: hclog.LevelFromString(logrus.GetLevel().String()),
|
||||
Level: hclog.LevelFromString(log.Logger.GetLevel().String()),
|
||||
JSONFormat: true,
|
||||
Output: logs.NoLevel(log.Logger, zerolog.DebugLevel),
|
||||
})
|
||||
|
||||
errChan := make(chan error, 2)
|
||||
|
@ -455,13 +457,13 @@ func (p *Provider) watchServices(ctx context.Context) error {
|
|||
func rootsWatchHandler(ctx context.Context, dest chan<- []string) func(watch.BlockingParamVal, interface{}) {
|
||||
return func(_ watch.BlockingParamVal, raw interface{}) {
|
||||
if raw == nil {
|
||||
log.FromContext(ctx).Errorf("Root certificate watcher called with nil")
|
||||
log.Ctx(ctx).Error().Msg("Root certificate watcher called with nil")
|
||||
return
|
||||
}
|
||||
|
||||
v, ok := raw.(*api.CARootList)
|
||||
if !ok || v == nil {
|
||||
log.FromContext(ctx).Errorf("Invalid result for root certificate watcher")
|
||||
log.Ctx(ctx).Error().Msg("Invalid result for root certificate watcher")
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -485,13 +487,13 @@ type keyPair struct {
|
|||
func leafWatcherHandler(ctx context.Context, dest chan<- keyPair) func(watch.BlockingParamVal, interface{}) {
|
||||
return func(_ watch.BlockingParamVal, raw interface{}) {
|
||||
if raw == nil {
|
||||
log.FromContext(ctx).Errorf("Leaf certificate watcher called with nil")
|
||||
log.Ctx(ctx).Error().Msg("Leaf certificate watcher called with nil")
|
||||
return
|
||||
}
|
||||
|
||||
v, ok := raw.(*api.LeafCert)
|
||||
if !ok || v == nil {
|
||||
log.FromContext(ctx).Errorf("Invalid result for leaf certificate watcher")
|
||||
log.Ctx(ctx).Error().Msg("Invalid result for leaf certificate watcher")
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -531,8 +533,9 @@ func (p *Provider) watchConnectTLS(ctx context.Context) error {
|
|||
|
||||
hclogger := hclog.New(&hclog.LoggerOptions{
|
||||
Name: "consulcatalog",
|
||||
Level: hclog.LevelFromString(logrus.GetLevel().String()),
|
||||
Level: hclog.LevelFromString(log.Logger.GetLevel().String()),
|
||||
JSONFormat: true,
|
||||
Output: logs.NoLevel(log.Logger, zerolog.DebugLevel),
|
||||
})
|
||||
|
||||
errChan := make(chan error, 2)
|
||||
|
@ -573,7 +576,7 @@ func (p *Provider) watchConnectTLS(ctx context.Context) error {
|
|||
leaf: leafCerts,
|
||||
}
|
||||
if newCertInfo.isReady() && !newCertInfo.equals(certInfo) {
|
||||
log.FromContext(ctx).Debugf("Updating connect certs for service %s", p.ServiceName)
|
||||
log.Ctx(ctx).Debug().Msgf("Updating connect certs for service %s", p.ServiceName)
|
||||
|
||||
certInfo = newCertInfo
|
||||
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue