From 5e2a1195d7a1f62be5ee49b6fc2850ada95d6f26 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sun, 30 Jul 2023 17:18:56 +0200 Subject: [PATCH] swap logrus types for their containerd/logs aliases Signed-off-by: Sebastiaan van Stijn --- api/server/httpstatus/status.go | 8 +- api/server/middleware.go | 4 +- api/server/router/swarm/cluster_routes.go | 17 +- cli/debug/debug.go | 6 +- cli/debug/debug_test.go | 26 +-- cmd/dockerd/daemon.go | 51 +++-- cmd/dockerd/daemon_test.go | 13 +- cmd/dockerd/docker.go | 4 +- .../cluster/controllers/plugin/controller.go | 2 +- daemon/cluster/executor/container/adapter.go | 20 +- daemon/cluster/executor/container/executor.go | 21 +- daemon/container_operations_unix.go | 5 +- daemon/container_operations_windows.go | 5 +- daemon/containerd/image_children.go | 17 +- daemon/containerd/image_exporter.go | 9 +- daemon/containerd/image_import.go | 3 +- daemon/containerd/image_list.go | 21 +- daemon/containerd/image_prune.go | 5 +- daemon/containerd/image_pull.go | 3 +- daemon/containerd/image_tag.go | 3 +- daemon/containerd/resolver.go | 3 +- daemon/containerd/service.go | 3 +- daemon/daemon.go | 46 ++--- daemon/images/store.go | 3 +- daemon/list.go | 12 +- daemon/logger/awslogs/cloudwatchlogs.go | 13 +- daemon/logger/loggerutils/follow.go | 2 +- daemon/logs.go | 3 +- daemon/monitor.go | 35 ++-- daemon/mounts.go | 3 +- daemon/network.go | 5 +- daemon/reload.go | 3 +- distribution/pull_v2.go | 10 +- image/store.go | 3 +- integration-cli/docker_cli_logs_test.go | 4 +- libcontainerd/local/local_windows.go | 36 ++-- libcontainerd/remote/client.go | 10 +- libcontainerd/remote/client_io_windows.go | 22 +-- libnetwork/cmd/diagnostic/main.go | 4 +- libnetwork/cmd/networkdb-test/testMain.go | 7 +- libnetwork/diagnostic/server.go | 63 +++--- libnetwork/drivers/overlay/ov_network.go | 17 +- libnetwork/networkdb/networkdb_test.go | 5 +- libnetwork/networkdb/networkdbdiagnostic.go | 182 ++++++++++++------ libnetwork/resolver.go | 6 +- pkg/archive/archive.go | 3 +- plugin/executor/containerd/containerd.go | 3 +- plugin/manager.go | 2 +- registry/config.go | 7 +- volume/local/local.go | 3 +- volume/mounts/mounts.go | 3 +- 51 files changed, 391 insertions(+), 373 deletions(-) diff --git a/api/server/httpstatus/status.go b/api/server/httpstatus/status.go index 456ec6e88b..54b817fb7c 100644 --- a/api/server/httpstatus/status.go +++ b/api/server/httpstatus/status.go @@ -9,7 +9,6 @@ import ( "github.com/containerd/containerd/log" "github.com/docker/distribution/registry/api/errcode" "github.com/docker/docker/errdefs" - "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -21,7 +20,7 @@ type causer interface { // FromError retrieves status code from error message. func FromError(err error) int { if err == nil { - log.G(context.TODO()).WithFields(logrus.Fields{"error": err}).Error("unexpected HTTP error handling") + log.G(context.TODO()).WithError(err).Error("unexpected HTTP error handling") return http.StatusInternalServerError } @@ -67,10 +66,11 @@ func FromError(err error) int { return FromError(e.Cause()) } - log.G(context.TODO()).WithFields(logrus.Fields{ + log.G(context.TODO()).WithFields(log.Fields{ "module": "api", + "error": err, "error_type": fmt.Sprintf("%T", err), - }).Debugf("FIXME: Got an API for which error does not match any expected type!!!: %+v", err) + }).Debug("FIXME: Got an API for which error does not match any expected type!!!") } if statusCode == 0 { diff --git a/api/server/middleware.go b/api/server/middleware.go index 10f3275bb1..0bb3601eb3 100644 --- a/api/server/middleware.go +++ b/api/server/middleware.go @@ -1,9 +1,9 @@ package server // import "github.com/docker/docker/api/server" import ( + "github.com/containerd/containerd/log" "github.com/docker/docker/api/server/httputils" "github.com/docker/docker/api/server/middleware" - "github.com/sirupsen/logrus" ) // handlerWithGlobalMiddlewares wraps the handler function for a request with @@ -16,7 +16,7 @@ func (s *Server) handlerWithGlobalMiddlewares(handler httputils.APIFunc) httputi next = m.WrapHandler(next) } - if logrus.GetLevel() == logrus.DebugLevel { + if log.GetLevel() == log.DebugLevel { next = middleware.DebugRequestMiddleware(next) } diff --git a/api/server/router/swarm/cluster_routes.go b/api/server/router/swarm/cluster_routes.go index 1f3dc9bf31..6ba56b4132 100644 --- a/api/server/router/swarm/cluster_routes.go +++ b/api/server/router/swarm/cluster_routes.go @@ -16,7 +16,6 @@ import ( "github.com/docker/docker/api/types/versions" "github.com/docker/docker/errdefs" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) func (sr *swarmRouter) initCluster(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { @@ -195,7 +194,7 @@ func (sr *swarmRouter) getService(ctx context.Context, w http.ResponseWriter, r service, err := sr.backend.GetService(vars["id"], insertDefaults) if err != nil { - log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithContext(ctx).WithFields(log.Fields{ "error": err, "service-id": vars["id"], }).Debug("Error getting service") @@ -231,7 +230,7 @@ func (sr *swarmRouter) createService(ctx context.Context, w http.ResponseWriter, resp, err := sr.backend.CreateService(service, encodedAuth, queryRegistry) if err != nil { - log.G(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithFields(log.Fields{ "error": err, "service-name": service.Name, }).Debug("Error creating service") @@ -270,7 +269,7 @@ func (sr *swarmRouter) updateService(ctx context.Context, w http.ResponseWriter, resp, err := sr.backend.UpdateService(vars["id"], version, service, flags, queryRegistry) if err != nil { - log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithContext(ctx).WithFields(log.Fields{ "error": err, "service-id": vars["id"], }).Debug("Error updating service") @@ -281,7 +280,7 @@ func (sr *swarmRouter) updateService(ctx context.Context, w http.ResponseWriter, func (sr *swarmRouter) removeService(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := sr.backend.RemoveService(vars["id"]); err != nil { - log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithContext(ctx).WithFields(log.Fields{ "error": err, "service-id": vars["id"], }).Debug("Error removing service") @@ -335,7 +334,7 @@ func (sr *swarmRouter) getNodes(ctx context.Context, w http.ResponseWriter, r *h func (sr *swarmRouter) getNode(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { node, err := sr.backend.GetNode(vars["id"]) if err != nil { - log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithContext(ctx).WithFields(log.Fields{ "error": err, "node-id": vars["id"], }).Debug("Error getting node") @@ -359,7 +358,7 @@ func (sr *swarmRouter) updateNode(ctx context.Context, w http.ResponseWriter, r } if err := sr.backend.UpdateNode(vars["id"], version, node); err != nil { - log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithContext(ctx).WithFields(log.Fields{ "error": err, "node-id": vars["id"], }).Debug("Error updating node") @@ -376,7 +375,7 @@ func (sr *swarmRouter) removeNode(ctx context.Context, w http.ResponseWriter, r force := httputils.BoolValue(r, "force") if err := sr.backend.RemoveNode(vars["id"], force); err != nil { - log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithContext(ctx).WithFields(log.Fields{ "error": err, "node-id": vars["id"], }).Debug("Error removing node") @@ -406,7 +405,7 @@ func (sr *swarmRouter) getTasks(ctx context.Context, w http.ResponseWriter, r *h func (sr *swarmRouter) getTask(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { task, err := sr.backend.GetTask(vars["id"]) if err != nil { - log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithContext(ctx).WithFields(log.Fields{ "error": err, "task-id": vars["id"], }).Debug("Error getting task") diff --git a/cli/debug/debug.go b/cli/debug/debug.go index 2303e15c99..0790e0c10e 100644 --- a/cli/debug/debug.go +++ b/cli/debug/debug.go @@ -3,21 +3,21 @@ package debug // import "github.com/docker/docker/cli/debug" import ( "os" - "github.com/sirupsen/logrus" + "github.com/containerd/containerd/log" ) // Enable sets the DEBUG env var to true // and makes the logger to log at debug level. func Enable() { os.Setenv("DEBUG", "1") - logrus.SetLevel(logrus.DebugLevel) + _ = log.SetLevel("debug") } // Disable sets the DEBUG env var to false // and makes the logger to log at info level. func Disable() { os.Setenv("DEBUG", "") - logrus.SetLevel(logrus.InfoLevel) + _ = log.SetLevel("info") } // IsEnabled checks whether the debug flag is set or not. diff --git a/cli/debug/debug_test.go b/cli/debug/debug_test.go index 72028a8e36..da0224c7dc 100644 --- a/cli/debug/debug_test.go +++ b/cli/debug/debug_test.go @@ -4,30 +4,30 @@ import ( "os" "testing" - "github.com/sirupsen/logrus" + "github.com/containerd/containerd/log" ) func TestEnable(t *testing.T) { - defer func() { - os.Setenv("DEBUG", "") - logrus.SetLevel(logrus.InfoLevel) - }() + t.Cleanup(func() { + _ = os.Setenv("DEBUG", "") + _ = log.SetLevel("info") + }) Enable() - if os.Getenv("DEBUG") != "1" { - t.Fatalf("expected DEBUG=1, got %s", os.Getenv("DEBUG")) + if debug := os.Getenv("DEBUG"); debug != "1" { + t.Fatalf("expected DEBUG=1, got %s", debug) } - if logrus.GetLevel() != logrus.DebugLevel { - t.Fatalf("expected log level %v, got %v", logrus.DebugLevel, logrus.GetLevel()) + if lvl := log.GetLevel(); lvl != log.DebugLevel { + t.Fatalf("expected log level %v, got %v", log.DebugLevel, lvl) } } func TestDisable(t *testing.T) { Disable() - if os.Getenv("DEBUG") != "" { - t.Fatalf(`expected DEBUG="", got %s`, os.Getenv("DEBUG")) + if debug := os.Getenv("DEBUG"); debug != "" { + t.Fatalf(`expected DEBUG="", got %s`, debug) } - if logrus.GetLevel() != logrus.InfoLevel { - t.Fatalf("expected log level %v, got %v", logrus.InfoLevel, logrus.GetLevel()) + if lvl := log.GetLevel(); lvl != log.InfoLevel { + t.Fatalf("expected log level %v, got %v", log.InfoLevel, lvl) } } diff --git a/cmd/dockerd/daemon.go b/cmd/dockerd/daemon.go index 50ea1d1522..e9f979c699 100644 --- a/cmd/dockerd/daemon.go +++ b/cmd/dockerd/daemon.go @@ -47,7 +47,6 @@ import ( dopts "github.com/docker/docker/opts" "github.com/docker/docker/pkg/authorization" "github.com/docker/docker/pkg/homedir" - "github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/pidfile" "github.com/docker/docker/pkg/plugingetter" "github.com/docker/docker/pkg/rootless" @@ -305,9 +304,9 @@ func (cli *DaemonCli) start(opts *daemonOptions) (err error) { defer apiWG.Done() log.G(ctx).Infof("API listen on %s", ls.Addr()) if err := httpServer.Serve(ls); err != http.ErrServerClosed { - log.G(ctx).WithFields(logrus.Fields{ - logrus.ErrorKey: err, - "listener": ls.Addr(), + log.G(ctx).WithFields(log.Fields{ + "error": err, + "listener": ls.Addr(), }).Error("ServeAPI error") select { @@ -861,37 +860,31 @@ func systemContainerdRunning(honorXDG bool) (string, bool, error) { return addr, err == nil, nil } -// configureDaemonLogs sets the logrus logging level and formatting. It expects +// configureDaemonLogs sets the logging level and formatting. It expects // the passed configuration to already be validated, and ignores invalid options. func configureDaemonLogs(conf *config.Config) { - if conf.LogLevel != "" { - lvl, err := logrus.ParseLevel(conf.LogLevel) - if err == nil { - logrus.SetLevel(lvl) - } - } else { - logrus.SetLevel(logrus.InfoLevel) - } - logFormat := conf.LogFormat - if logFormat == "" { - logFormat = log.TextFormat - } - var formatter logrus.Formatter - switch logFormat { + switch conf.LogFormat { case log.JSONFormat: - formatter = &logrus.JSONFormatter{ - TimestampFormat: jsonmessage.RFC3339NanoFixed, - } - case log.TextFormat: - formatter = &logrus.TextFormatter{ - TimestampFormat: jsonmessage.RFC3339NanoFixed, + logrus.SetFormatter(&logrus.JSONFormatter{ + TimestampFormat: log.RFC3339NanoFixed, + }) + case log.TextFormat, "": + logrus.SetFormatter(&logrus.TextFormatter{ + TimestampFormat: log.RFC3339NanoFixed, DisableColors: conf.RawLogs, FullTimestamp: true, - } + }) default: - panic("unsupported log format " + logFormat) + panic("unsupported log format " + conf.LogFormat) + } + + logLevel := conf.LogLevel + if logLevel == "" { + logLevel = "info" + } + if err := log.SetLevel(logLevel); err != nil { + log.G(context.TODO()).WithError(err).Warn("configure log level") } - logrus.SetFormatter(formatter) } func configureProxyEnv(conf *config.Config) { @@ -911,7 +904,7 @@ func configureProxyEnv(conf *config.Config) { func overrideProxyEnv(name, val string) { if oldVal := os.Getenv(name); oldVal != "" && oldVal != val { - log.G(context.TODO()).WithFields(logrus.Fields{ + log.G(context.TODO()).WithFields(log.Fields{ "name": name, "old-value": config.MaskCredentials(oldVal), "new-value": config.MaskCredentials(val), diff --git a/cmd/dockerd/daemon_test.go b/cmd/dockerd/daemon_test.go index 7f8d2c7383..55b301f8db 100644 --- a/cmd/dockerd/daemon_test.go +++ b/cmd/dockerd/daemon_test.go @@ -211,14 +211,15 @@ func TestLoadDaemonConfigWithRegistryOptions(t *testing.T) { func TestConfigureDaemonLogs(t *testing.T) { conf := &config.Config{} configureDaemonLogs(conf) - assert.Check(t, is.Equal(logrus.InfoLevel, logrus.GetLevel())) - - conf.LogLevel = "warn" - configureDaemonLogs(conf) - assert.Check(t, is.Equal(logrus.WarnLevel, logrus.GetLevel())) + assert.Check(t, is.Equal(log.InfoLevel, log.GetLevel())) // log level should not be changed when passing an invalid value conf.LogLevel = "foobar" configureDaemonLogs(conf) - assert.Check(t, is.Equal(logrus.WarnLevel, logrus.GetLevel())) + assert.Check(t, is.Equal(log.InfoLevel, log.GetLevel())) + + conf.LogLevel = "warn" + configureDaemonLogs(conf) + // TODO (thaJeztah): add more aliases in log package + assert.Check(t, is.Equal(logrus.WarnLevel, log.GetLevel())) } diff --git a/cmd/dockerd/docker.go b/cmd/dockerd/docker.go index b2e199f473..08006571df 100644 --- a/cmd/dockerd/docker.go +++ b/cmd/dockerd/docker.go @@ -6,9 +6,9 @@ import ( "os/signal" "syscall" + "github.com/containerd/containerd/log" "github.com/docker/docker/daemon/config" "github.com/docker/docker/dockerversion" - "github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/reexec" "github.com/docker/docker/pkg/rootless" "github.com/moby/buildkit/util/apicaps" @@ -84,7 +84,7 @@ func main() { // initial log formatting; this setting is updated after the daemon configuration is loaded. logrus.SetFormatter(&logrus.TextFormatter{ - TimestampFormat: jsonmessage.RFC3339NanoFixed, + TimestampFormat: log.RFC3339NanoFixed, FullTimestamp: true, }) diff --git a/daemon/cluster/controllers/plugin/controller.go b/daemon/cluster/controllers/plugin/controller.go index 9b182996b4..16768d8c49 100644 --- a/daemon/cluster/controllers/plugin/controller.go +++ b/daemon/cluster/controllers/plugin/controller.go @@ -62,7 +62,7 @@ func NewController(backend Backend, t *api.Task) (*Controller, error) { backend: backend, spec: spec, serviceID: t.ServiceID, - logger: log.G(context.TODO()).WithFields(logrus.Fields{ + logger: log.G(context.TODO()).WithFields(log.Fields{ "controller": "plugin", "task": t.ID, "plugin": spec.Name, diff --git a/daemon/cluster/executor/container/adapter.go b/daemon/cluster/executor/container/adapter.go index 49269be40e..a4fc40deef 100644 --- a/daemon/cluster/executor/container/adapter.go +++ b/daemon/cluster/executor/container/adapter.go @@ -11,6 +11,7 @@ import ( "syscall" "time" + "github.com/containerd/containerd/log" "github.com/docker/distribution/reference" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/backend" @@ -27,10 +28,9 @@ import ( gogotypes "github.com/gogo/protobuf/types" "github.com/moby/swarmkit/v2/agent/exec" "github.com/moby/swarmkit/v2/api" - "github.com/moby/swarmkit/v2/log" + swarmlog "github.com/moby/swarmkit/v2/log" "github.com/opencontainers/go-digest" "github.com/pkg/errors" - "github.com/sirupsen/logrus" "golang.org/x/time/rate" ) @@ -95,7 +95,7 @@ func (c *containerAdapter) pullImage(ctx context.Context) error { authConfig := ®istry.AuthConfig{} if encodedAuthConfig != "" { if err := json.NewDecoder(base64.NewDecoder(base64.URLEncoding, strings.NewReader(encodedAuthConfig))).Decode(authConfig); err != nil { - log.G(ctx).Warnf("invalid authconfig: %v", err) + swarmlog.G(ctx).Warnf("invalid authconfig: %v", err) } } @@ -121,19 +121,19 @@ func (c *containerAdapter) pullImage(ctx context.Context) error { } return err } - l := log.G(ctx) + l := swarmlog.G(ctx) // limit pull progress logs unless the status changes if spamLimiter.Allow() || lastStatus != m["status"] { // if we have progress details, we have everything we need if progress, ok := m["progressDetail"].(map[string]interface{}); ok { // first, log the image and status - l = l.WithFields(logrus.Fields{ + l = l.WithFields(log.Fields{ "image": c.container.image(), "status": m["status"], }) // then, if we have progress, log the progress if progress["current"] != nil && progress["total"] != nil { - l = l.WithFields(logrus.Fields{ + l = l.WithFields(log.Fields{ "current": progress["current"], "total": progress["total"], }) @@ -240,7 +240,7 @@ func (c *containerAdapter) removeNetworks(ctx context.Context) error { case errors.As(err, &errNoSuchNetwork): continue default: - log.G(ctx).Errorf("network %s remove failed: %v", name, err) + swarmlog.G(ctx).Errorf("network %s remove failed: %v", name, err) return err } } @@ -374,7 +374,7 @@ func (c *containerAdapter) inspect(ctx context.Context) (types.ContainerJSON, er // events issues a call to the events API and returns a channel with all // events. The stream of events can be shutdown by cancelling the context. func (c *containerAdapter) events(ctx context.Context) <-chan events.Message { - log.G(ctx).Debugf("waiting on events") + swarmlog.G(ctx).Debugf("waiting on events") buffer, l := c.backend.SubscribeToEvents(time.Time{}, time.Time{}, c.container.eventFilter()) eventsq := make(chan events.Message, len(buffer)) @@ -390,7 +390,7 @@ func (c *containerAdapter) events(ctx context.Context) <-chan events.Message { case ev := <-l: jev, ok := ev.(events.Message) if !ok { - log.G(ctx).Warnf("unexpected event message: %q", ev) + swarmlog.G(ctx).Warnf("unexpected event message: %q", ev) continue } select { @@ -485,7 +485,7 @@ func (c *containerAdapter) waitClusterVolumes(ctx context.Context) error { } } } - log.G(ctx).Debug("volumes ready") + swarmlog.G(ctx).Debug("volumes ready") return nil } diff --git a/daemon/cluster/executor/container/executor.go b/daemon/cluster/executor/container/executor.go index 2cec252e73..e8325c3ef8 100644 --- a/daemon/cluster/executor/container/executor.go +++ b/daemon/cluster/executor/container/executor.go @@ -7,6 +7,7 @@ import ( "strings" "sync" + "github.com/containerd/containerd/log" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/network" @@ -21,10 +22,9 @@ import ( "github.com/moby/swarmkit/v2/agent/exec" "github.com/moby/swarmkit/v2/api" "github.com/moby/swarmkit/v2/api/naming" - "github.com/moby/swarmkit/v2/log" + swarmlog "github.com/moby/swarmkit/v2/log" "github.com/moby/swarmkit/v2/template" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) type executor struct { @@ -160,8 +160,7 @@ func (e *executor) Configure(ctx context.Context, node *api.Node) error { if na == nil || na.Network == nil || len(na.Addresses) == 0 { // this should not happen, but we got a panic here and don't have a // good idea about what the underlying data structure looks like. - log.G(ctx).WithField("NetworkAttachment", fmt.Sprintf("%#v", na)). - Warnf("skipping nil or malformed node network attachment entry") + swarmlog.G(ctx).WithField("NetworkAttachment", fmt.Sprintf("%#v", na)).Warn("skipping nil or malformed node network attachment entry") continue } @@ -192,8 +191,7 @@ func (e *executor) Configure(ctx context.Context, node *api.Node) error { // same thing as above, check sanity of the attachments so we don't // get a panic. if na == nil || na.Network == nil || len(na.Addresses) == 0 { - log.G(ctx).WithField("NetworkAttachment", fmt.Sprintf("%#v", na)). - Warnf("skipping nil or malformed node network attachment entry") + swarmlog.G(ctx).WithField("NetworkAttachment", fmt.Sprintf("%#v", na)).Warn("skipping nil or malformed node network attachment entry") continue } @@ -262,19 +260,16 @@ func (e *executor) Configure(ctx context.Context, node *api.Node) error { // just to log an appropriate, informative error. i'm unsure if // this can ever actually occur, but we need to know if it does. if gone { - log.G(ctx).Warnf("network %s should be removed, but still has active attachments", nw) + swarmlog.G(ctx).Warnf("network %s should be removed, but still has active attachments", nw) } else { - log.G(ctx).Warnf( - "network %s should have its node LB IP changed, but cannot be removed because of active attachments", - nw, - ) + swarmlog.G(ctx).Warnf("network %s should have its node LB IP changed, but cannot be removed because of active attachments", nw) } continue case errors.As(err, &errNoSuchNetwork): // NoSuchNetworkError indicates the network is already gone. continue default: - log.G(ctx).Errorf("network %s remove failed: %v", nw, err) + swarmlog.G(ctx).Errorf("network %s remove failed: %v", nw, err) } } @@ -301,7 +296,7 @@ func (e *executor) Controller(t *api.Task) (exec.Controller, error) { var ctlr exec.Controller switch r := t.Spec.GetRuntime().(type) { case *api.TaskSpec_Generic: - log.G(context.TODO()).WithFields(logrus.Fields{ + swarmlog.G(context.TODO()).WithFields(log.Fields{ "kind": r.Generic.Kind, "type_url": r.Generic.Payload.TypeUrl, }).Debug("custom runtime requested") diff --git a/daemon/container_operations_unix.go b/daemon/container_operations_unix.go index 2277889ab9..5002cb431b 100644 --- a/daemon/container_operations_unix.go +++ b/daemon/container_operations_unix.go @@ -23,7 +23,6 @@ import ( "github.com/moby/sys/mount" "github.com/opencontainers/selinux/go-selinux/label" "github.com/pkg/errors" - "github.com/sirupsen/logrus" "golang.org/x/sys/unix" ) @@ -200,7 +199,7 @@ func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) { return errors.Wrap(err, "error creating secret mount path") } - log.G(context.TODO()).WithFields(logrus.Fields{ + log.G(context.TODO()).WithFields(log.Fields{ "name": s.File.Name, "path": fPath, }).Debug("injecting secret") @@ -251,7 +250,7 @@ func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) { return errors.Wrap(err, "error creating config mount path") } - log.G(context.TODO()).WithFields(logrus.Fields{ + log.G(context.TODO()).WithFields(log.Fields{ "name": configRef.File.Name, "path": fPath, }).Debug("injecting config") diff --git a/daemon/container_operations_windows.go b/daemon/container_operations_windows.go index 9dc5461847..6c984c4991 100644 --- a/daemon/container_operations_windows.go +++ b/daemon/container_operations_windows.go @@ -11,7 +11,6 @@ import ( "github.com/docker/docker/libnetwork" "github.com/docker/docker/pkg/system" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) func (daemon *Daemon) setupLinkedContainers(container *container.Container) ([]string, error) { @@ -61,7 +60,7 @@ func (daemon *Daemon) setupConfigDir(c *container.Container) (setupErr error) { if err != nil { return errors.Wrap(err, "error getting config file path for container") } - log := log.G(context.TODO()).WithFields(logrus.Fields{"name": configRef.File.Name, "path": fPath}) + log := log.G(context.TODO()).WithFields(log.Fields{"name": configRef.File.Name, "path": fPath}) log.Debug("injecting config") config, err := c.DependencyStore.Configs().Get(configRef.ConfigID) @@ -131,7 +130,7 @@ func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) { if err != nil { return err } - log.G(context.TODO()).WithFields(logrus.Fields{ + log.G(context.TODO()).WithFields(log.Fields{ "name": s.File.Name, "path": fPath, }).Debug("injecting secret") diff --git a/daemon/containerd/image_children.go b/daemon/containerd/image_children.go index 992d318602..4f39d43f54 100644 --- a/daemon/containerd/image_children.go +++ b/daemon/containerd/image_children.go @@ -12,7 +12,6 @@ import ( "github.com/docker/docker/image" ocispec "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) // Children returns a slice of image ID which rootfs is a superset of the @@ -36,10 +35,10 @@ func (i *ImageService) Children(ctx context.Context, id image.ID) ([]image.ID, e rootfs, err := platformRootfs(ctx, cs, target, platform) if err != nil { if !cerrdefs.IsNotFound(err) { - log.G(ctx).WithFields(logrus.Fields{ - logrus.ErrorKey: err, - "image": target.Digest, - "platform": platform, + log.G(ctx).WithFields(log.Fields{ + "error": err, + "image": target.Digest, + "platform": platform, }).Warning("failed to get platform-specific rootfs") } continue @@ -60,10 +59,10 @@ func (i *ImageService) Children(ctx context.Context, id image.ID) ([]image.ID, e rootfs, err := platformRootfs(ctx, cs, img.Target, platform) if err != nil { if !cerrdefs.IsNotFound(err) { - log.G(ctx).WithFields(logrus.Fields{ - logrus.ErrorKey: err, - "image": img.Target.Digest, - "platform": platform, + log.G(ctx).WithFields(log.Fields{ + "error": err, + "image": img.Target.Digest, + "platform": platform, }).Warning("failed to get platform-specific rootfs") } continue diff --git a/daemon/containerd/image_exporter.go b/daemon/containerd/image_exporter.go index 521ae21ff8..bb6011ee67 100644 --- a/daemon/containerd/image_exporter.go +++ b/daemon/containerd/image_exporter.go @@ -22,7 +22,6 @@ import ( "github.com/opencontainers/image-spec/specs-go" ocispec "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) func (i *ImageService) PerformWithBaseFS(ctx context.Context, c *container.Container, fn func(root string) error) error { @@ -97,14 +96,14 @@ func (i *ImageService) ExportImage(ctx context.Context, names []string, outStrea ref = reference.TagNameOnly(ref) opts = append(opts, archive.WithManifest(target, ref.String())) - log.G(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithFields(log.Fields{ "target": target, "name": ref.String(), }).Debug("export image") } else { opts = append(opts, archive.WithManifest(target)) - log.G(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithFields(log.Fields{ "target": target, }).Debug("export image without name") } @@ -177,7 +176,7 @@ func (i *ImageService) LoadImage(ctx context.Context, inTar io.ReadCloser, outSt } err = i.walkImageManifests(ctx, img, func(platformImg *ImageManifest) error { - logger := log.G(ctx).WithFields(logrus.Fields{ + logger := log.G(ctx).WithFields(log.Fields{ "image": name, "manifest": platformImg.Target().Digest, }) @@ -259,7 +258,7 @@ func (i *ImageService) getBestDescriptorForExport(ctx context.Context, indexDesc log.G(ctx).WithField("manifest", mfst.Digest).Debug("manifest content present, will export") } else { hasMissingManifests = true - log.G(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithFields(log.Fields{ "manifest": mfst.Digest, "missing": missing, }).Debug("manifest is missing, won't export") diff --git a/daemon/containerd/image_import.go b/daemon/containerd/image_import.go index ff9242472d..339c581820 100644 --- a/daemon/containerd/image_import.go +++ b/daemon/containerd/image_import.go @@ -26,7 +26,6 @@ import ( "github.com/opencontainers/image-spec/specs-go" ocispec "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) // ImportImage imports an image, getting the archived layer data from layerReader. @@ -67,7 +66,7 @@ func (i *ImageService) ImportImage(ctx context.Context, ref reference.Named, pla logger.WithError(err).Debug("failed to write layer blob") return "", err } - logger = logger.WithFields(logrus.Fields{ + logger = logger.WithFields(log.Fields{ "compressedDigest": compressedDigest, "uncompressedDigest": uncompressedDigest, }) diff --git a/daemon/containerd/image_list.go b/daemon/containerd/image_list.go index dec60face1..d4b038e3e6 100644 --- a/daemon/containerd/image_list.go +++ b/daemon/containerd/image_list.go @@ -23,7 +23,6 @@ import ( "github.com/opencontainers/image-spec/identity" ocispec "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) // Subset of ocispec.Image that only contains Labels @@ -127,10 +126,10 @@ func (i *ImageService) Images(ctx context.Context, opts types.ImageListOptions) available, err := img.CheckContentAvailable(ctx) if err != nil { - log.G(ctx).WithFields(logrus.Fields{ - logrus.ErrorKey: err, - "manifest": img.Target(), - "image": img.Name(), + log.G(ctx).WithFields(log.Fields{ + "error": err, + "manifest": img.Target(), + "image": img.Name(), }).Warn("checking availability of platform specific manifest failed") return nil } @@ -189,7 +188,7 @@ func (i *ImageService) singlePlatformImage(ctx context.Context, contentStore con unpackedUsage, err := calculateSnapshotTotalUsage(ctx, snapshotter, imageSnapshotID) if err != nil { if !cerrdefs.IsNotFound(err) { - log.G(ctx).WithError(err).WithFields(logrus.Fields{ + log.G(ctx).WithError(err).WithFields(log.Fields{ "image": image.Name(), "snapshotID": imageSnapshotID, }).Warn("failed to calculate unpacked size of image") @@ -210,7 +209,7 @@ func (i *ImageService) singlePlatformImage(ctx context.Context, contentStore con rawImg := image.Metadata() target := rawImg.Target.Digest - logger := log.G(ctx).WithFields(logrus.Fields{ + logger := log.G(ctx).WithFields(log.Fields{ "name": rawImg.Name, "digest": target, }) @@ -469,10 +468,10 @@ func setupLabelFilter(store content.Store, fltrs filters.Args) (func(image image return true } if err != nil { - log.G(ctx).WithFields(logrus.Fields{ - logrus.ErrorKey: err, - "image": image.Name, - "checks": checks, + log.G(ctx).WithFields(log.Fields{ + "error": err, + "image": image.Name, + "checks": checks, }).Error("failed to check image labels") } diff --git a/daemon/containerd/image_prune.go b/daemon/containerd/image_prune.go index 719876cc29..9146bff5c1 100644 --- a/daemon/containerd/image_prune.go +++ b/daemon/containerd/image_prune.go @@ -15,7 +15,6 @@ import ( "github.com/opencontainers/go-digest" ocispec "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) var imagesAcceptedFilters = map[string]bool{ @@ -80,7 +79,7 @@ func (i *ImageService) pruneUnused(ctx context.Context, filterFunc imageFilterFu if !danglingOnly || isDanglingImage(img) { canBePruned := filterFunc(img) - log.G(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithFields(log.Fields{ "image": img.Name, "canBePruned": canBePruned, }).Debug("considering image for pruning") @@ -116,7 +115,7 @@ func (i *ImageService) pruneUnused(ctx context.Context, filterFunc imageFilterFu } ref, err := reference.ParseNormalizedNamed(ctr.Config.Image) - log.G(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithFields(log.Fields{ "ctr": ctr.ID, "image": ref, "nameParseErr": err, diff --git a/daemon/containerd/image_pull.go b/daemon/containerd/image_pull.go index d8c1626335..ea133de18c 100644 --- a/daemon/containerd/image_pull.go +++ b/daemon/containerd/image_pull.go @@ -16,7 +16,6 @@ import ( "github.com/docker/docker/pkg/streamformatter" "github.com/opencontainers/go-digest" ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/sirupsen/logrus" ) // PullImage initiates a pull operation. image is the repository name to pull, and @@ -76,7 +75,7 @@ func (i *ImageService) PullImage(ctx context.Context, image, tagOrDigest string, return err } - logger := log.G(ctx).WithFields(logrus.Fields{ + logger := log.G(ctx).WithFields(log.Fields{ "digest": img.Target().Digest, "remote": ref.String(), }) diff --git a/daemon/containerd/image_tag.go b/daemon/containerd/image_tag.go index 79ce2895ce..5fcdecd79f 100644 --- a/daemon/containerd/image_tag.go +++ b/daemon/containerd/image_tag.go @@ -10,7 +10,6 @@ import ( "github.com/docker/docker/errdefs" "github.com/docker/docker/image" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) // TagImage creates an image named as newTag and targeting the given descriptor id. @@ -55,7 +54,7 @@ func (i *ImageService) TagImage(ctx context.Context, imageID image.ID, newTag re } } - logger := log.G(ctx).WithFields(logrus.Fields{ + logger := log.G(ctx).WithFields(log.Fields{ "imageID": imageID.String(), "tag": newTag.String(), }) diff --git a/daemon/containerd/resolver.go b/daemon/containerd/resolver.go index 3ed3d19625..7f7ee13456 100644 --- a/daemon/containerd/resolver.go +++ b/daemon/containerd/resolver.go @@ -14,7 +14,6 @@ import ( "github.com/docker/docker/dockerversion" "github.com/docker/docker/pkg/useragent" "github.com/docker/docker/registry" - "github.com/sirupsen/logrus" ) func (i *ImageService) newResolverFromAuthConfig(ctx context.Context, authConfig *registrytypes.AuthConfig) (remotes.Resolver, docker.StatusTracker) { @@ -64,7 +63,7 @@ func authorizationCredsFromAuthConfig(authConfig registrytypes.AuthConfig) docke return docker.WithAuthCreds(func(host string) (string, string, error) { if cfgHost != host { - log.G(context.TODO()).WithFields(logrus.Fields{ + log.G(context.TODO()).WithFields(log.Fields{ "host": host, "cfgHost": cfgHost, }).Warn("Host doesn't match") diff --git a/daemon/containerd/service.go b/daemon/containerd/service.go index f49bb86b54..4f86eac76f 100644 --- a/daemon/containerd/service.go +++ b/daemon/containerd/service.go @@ -22,7 +22,6 @@ import ( "github.com/docker/docker/registry" ocispec "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) // ImageService implements daemon.ImageService @@ -175,7 +174,7 @@ func (i *ImageService) GetContainerLayerSize(ctx context.Context, containerID st log.G(ctx).WithError(err).WithField("ctr", containerID).Warn("unexpected error when calculating usage of the parent snapshots") } } - log.G(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithFields(log.Fields{ "rwLayerUsage": rwLayerUsage.Size, "unpacked": unpackedUsage.Size, }).Debug("GetContainerLayerSize") diff --git a/daemon/daemon.go b/daemon/daemon.go index 1f45c0c1c6..a8abfe2c70 100644 --- a/daemon/daemon.go +++ b/daemon/daemon.go @@ -192,7 +192,7 @@ func (daemon *Daemon) UsesSnapshotter() bool { // RegistryHosts returns the registry hosts configuration for the host component // of a distribution image reference. func (daemon *Daemon) RegistryHosts(host string) ([]docker.RegistryHost, error) { - var m = map[string]resolverconfig.RegistryConfig{} + m := map[string]resolverconfig.RegistryConfig{} mirrors := daemon.registryService.ServiceConfig().Mirrors m["docker.io"] = resolverconfig.RegistryConfig{Mirrors: mirrors} @@ -268,27 +268,27 @@ func (daemon *Daemon) restore(cfg *configStore) error { _ = sem.Acquire(context.Background(), 1) defer sem.Release(1) - log := log.G(context.TODO()).WithField("container", id) + logger := log.G(context.TODO()).WithField("container", id) c, err := daemon.load(id) if err != nil { - log.WithError(err).Error("failed to load container") + logger.WithError(err).Error("failed to load container") return } if c.Driver != daemon.imageService.StorageDriver() { // Ignore the container if it wasn't created with the current storage-driver - log.Debugf("not restoring container because it was created with another storage driver (%s)", c.Driver) + logger.Debugf("not restoring container because it was created with another storage driver (%s)", c.Driver) return } if accessor, ok := daemon.imageService.(layerAccessor); ok { rwlayer, err := accessor.GetLayerByID(c.ID) if err != nil { - log.WithError(err).Error("failed to load container mount") + logger.WithError(err).Error("failed to load container mount") return } c.RWLayer = rwlayer } - log.WithFields(logrus.Fields{ + logger.WithFields(log.Fields{ "running": c.IsRunning(), "paused": c.IsPaused(), }).Debug("loaded container") @@ -311,17 +311,17 @@ func (daemon *Daemon) restore(cfg *configStore) error { _ = sem.Acquire(context.Background(), 1) defer sem.Release(1) - log := log.G(context.TODO()).WithField("container", c.ID) + logger := log.G(context.TODO()).WithField("container", c.ID) if err := daemon.registerName(c); err != nil { - log.WithError(err).Errorf("failed to register container name: %s", c.Name) + logger.WithError(err).Errorf("failed to register container name: %s", c.Name) mapLock.Lock() delete(containers, c.ID) mapLock.Unlock() return } if err := daemon.Register(c); err != nil { - log.WithError(err).Error("failed to register container") + logger.WithError(err).Error("failed to register container") mapLock.Lock() delete(containers, c.ID) mapLock.Unlock() @@ -338,16 +338,16 @@ func (daemon *Daemon) restore(cfg *configStore) error { _ = sem.Acquire(context.Background(), 1) defer sem.Release(1) - log := log.G(context.TODO()).WithField("container", c.ID) + baseLogger := log.G(context.TODO()).WithField("container", c.ID) if err := daemon.checkpointAndSave(c); err != nil { - log.WithError(err).Error("error saving backported mountspec to disk") + baseLogger.WithError(err).Error("error saving backported mountspec to disk") } daemon.setStateCounter(c) logger := func(c *container.Container) *logrus.Entry { - return log.WithFields(logrus.Fields{ + return baseLogger.WithFields(log.Fields{ "running": c.IsRunning(), "paused": c.IsPaused(), "restarting": c.IsRestarting(), @@ -382,7 +382,7 @@ func (daemon *Daemon) restore(cfg *configStore) error { } else if !cfg.LiveRestoreEnabled { logger(c).Debug("shutting down container considered alive by containerd") if err := daemon.shutdownContainer(c); err != nil && !errdefs.IsNotFound(err) { - log.WithError(err).Error("error shutting down container") + baseLogger.WithError(err).Error("error shutting down container") return } status = containerd.Stopped @@ -406,7 +406,7 @@ func (daemon *Daemon) restore(cfg *configStore) error { case containerd.Paused, containerd.Pausing: // nothing to do case containerd.Unknown, containerd.Stopped, "": - log.WithField("status", status).Error("unexpected status for paused container during restore") + baseLogger.WithField("status", status).Error("unexpected status for paused container during restore") default: // running c.Lock() @@ -414,7 +414,7 @@ func (daemon *Daemon) restore(cfg *configStore) error { daemon.setStateCounter(c) daemon.updateHealthMonitor(c) if err := c.CheckpointTo(daemon.containersReplica); err != nil { - log.WithError(err).Error("failed to update paused container state") + baseLogger.WithError(err).Error("failed to update paused container state") } c.Unlock() } @@ -438,7 +438,7 @@ func (daemon *Daemon) restore(cfg *configStore) error { c.SetStopped(&ces) daemon.Cleanup(c) if err := c.CheckpointTo(daemon.containersReplica); err != nil { - log.WithError(err).Error("failed to update stopped container state") + baseLogger.WithError(err).Error("failed to update stopped container state") } c.Unlock() logger(c).Debug("set stopped state") @@ -502,9 +502,9 @@ func (daemon *Daemon) restore(cfg *configStore) error { c.RemovalInProgress = false c.Dead = true if err := c.CheckpointTo(daemon.containersReplica); err != nil { - log.WithError(err).Error("failed to update RemovalInProgress container state") + baseLogger.WithError(err).Error("failed to update RemovalInProgress container state") } else { - log.Debugf("reset RemovalInProgress state for container") + baseLogger.Debugf("reset RemovalInProgress state for container") } } c.Unlock() @@ -1170,7 +1170,7 @@ func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S engineCpus.Set(float64(info.NCPU)) engineMemory.Set(float64(info.MemTotal)) - log.G(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithFields(log.Fields{ "version": dockerversion.Version, "commit": dockerversion.GitCommit, "graphdriver": d.ImageService().StorageDriver(), @@ -1256,16 +1256,16 @@ func (daemon *Daemon) Shutdown(ctx context.Context) error { if !c.IsRunning() { return } - log := log.G(ctx).WithField("container", c.ID) - log.Debug("shutting down container") + logger := log.G(ctx).WithField("container", c.ID) + logger.Debug("shutting down container") if err := daemon.shutdownContainer(c); err != nil { - log.WithError(err).Error("failed to shut down container") + logger.WithError(err).Error("failed to shut down container") return } if mountid, err := daemon.imageService.GetLayerMountID(c.ID); err == nil { daemon.cleanupMountsByID(mountid) } - log.Debugf("shut down container") + logger.Debugf("shut down container") }) } diff --git a/daemon/images/store.go b/daemon/images/store.go index 19d5d975e7..637c74628e 100644 --- a/daemon/images/store.go +++ b/daemon/images/store.go @@ -14,7 +14,6 @@ import ( "github.com/docker/docker/layer" "github.com/opencontainers/go-digest" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) const imageKeyPrefix = "moby-image-" @@ -83,7 +82,7 @@ func (s *imageStoreForPull) updateLease(ctx context.Context, dgst digest.Digest) Type: "content", } for _, dgst := range digested { - log.G(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithFields(log.Fields{ "digest": dgst, "lease": lease.ID, }).Debug("Adding content digest to lease") diff --git a/daemon/list.go b/daemon/list.go index 7da50858da..03adb394e6 100644 --- a/daemon/list.go +++ b/daemon/list.go @@ -16,7 +16,6 @@ import ( "github.com/docker/docker/image" "github.com/docker/go-connections/nat" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) var acceptedPsFilterTags = map[string]bool{ @@ -619,17 +618,16 @@ func (daemon *Daemon) refreshImage(ctx context.Context, s *container.Snapshot) ( // Check if the image reference still resolves to the same digest. img, err := daemon.imageService.GetImage(ctx, s.Image, imagetypes.GetImageOpts{}) - // If the image is no longer found or can't be resolved for some other // reason. Update the Image to the specific ID of the original image it // resolved to when the container was created. if err != nil { if !errdefs.IsNotFound(err) { - log.G(ctx).WithFields(logrus.Fields{ - logrus.ErrorKey: err, - "containerID": c.ID, - "image": s.Image, - "imageID": s.ImageID, + log.G(ctx).WithFields(log.Fields{ + "error": err, + "containerID": c.ID, + "image": s.Image, + "imageID": s.ImageID, }).Warn("failed to resolve container image") } c.Image = s.ImageID diff --git a/daemon/logger/awslogs/cloudwatchlogs.go b/daemon/logger/awslogs/cloudwatchlogs.go index 425c7b4e07..d56961edd9 100644 --- a/daemon/logger/awslogs/cloudwatchlogs.go +++ b/daemon/logger/awslogs/cloudwatchlogs.go @@ -27,7 +27,6 @@ import ( "github.com/docker/docker/daemon/logger/loggerutils" "github.com/docker/docker/dockerversion" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) const ( @@ -378,7 +377,7 @@ func newAWSLogsClient(info logger.Info, configOpts ...func(*config.LoadOptions) return nil, errors.Wrap(err, "could not initialize AWS SDK config") } - log.G(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithFields(log.Fields{ "region": *region, }).Debug("Created awslogs client") @@ -477,7 +476,7 @@ func (l *logStream) createLogGroup() error { }); err != nil { var apiErr smithy.APIError if errors.As(err, &apiErr) { - fields := logrus.Fields{ + fields := log.Fields{ "errorCode": apiErr.ErrorCode(), "message": apiErr.ErrorMessage(), "logGroupName": l.logGroupName, @@ -499,7 +498,7 @@ func (l *logStream) createLogGroup() error { func (l *logStream) createLogStream() error { // Directly return if we do not want to create log stream. if !l.logCreateStream { - log.G(context.TODO()).WithFields(logrus.Fields{ + log.G(context.TODO()).WithFields(log.Fields{ "logGroupName": l.logGroupName, "logStreamName": l.logStreamName, "logCreateStream": l.logCreateStream, @@ -516,7 +515,7 @@ func (l *logStream) createLogStream() error { if err != nil { var apiErr smithy.APIError if errors.As(err, &apiErr) { - fields := logrus.Fields{ + fields := log.Fields{ "errorCode": apiErr.ErrorCode(), "message": apiErr.ErrorMessage(), "logGroupName": l.logGroupName, @@ -695,7 +694,7 @@ func (l *logStream) publishBatch(batch *eventBatch) { if apiErr := (*types.DataAlreadyAcceptedException)(nil); errors.As(err, &apiErr) { // already submitted, just grab the correct sequence token nextSequenceToken = apiErr.ExpectedSequenceToken - log.G(context.TODO()).WithFields(logrus.Fields{ + log.G(context.TODO()).WithFields(log.Fields{ "errorCode": apiErr.ErrorCode(), "message": apiErr.ErrorMessage(), "logGroupName": l.logGroupName, @@ -725,7 +724,7 @@ func (l *logStream) putLogEvents(events []types.InputLogEvent, sequenceToken *st if err != nil { var apiErr smithy.APIError if errors.As(err, &apiErr) { - log.G(context.TODO()).WithFields(logrus.Fields{ + log.G(context.TODO()).WithFields(log.Fields{ "errorCode": apiErr.ErrorCode(), "message": apiErr.ErrorMessage(), "logGroupName": l.logGroupName, diff --git a/daemon/logger/loggerutils/follow.go b/daemon/logger/loggerutils/follow.go index c9a58dff7c..35f477db97 100644 --- a/daemon/logger/loggerutils/follow.go +++ b/daemon/logger/loggerutils/follow.go @@ -24,7 +24,7 @@ type follow struct { // Do follows the log file as it is written, starting from f at read. func (fl *follow) Do(f *os.File, read logPos) { - fl.log = log.G(context.TODO()).WithFields(logrus.Fields{ + fl.log = log.G(context.TODO()).WithFields(log.Fields{ "module": "logger", "file": f.Name(), }) diff --git a/daemon/logs.go b/daemon/logs.go index 8ceefb9422..20c7ffa26d 100644 --- a/daemon/logs.go +++ b/daemon/logs.go @@ -16,7 +16,6 @@ import ( logcache "github.com/docker/docker/daemon/logger/loggerutils/cache" "github.com/docker/docker/errdefs" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) // ContainerLogs copies the container's log channel to the channel provided in @@ -26,7 +25,7 @@ import ( // if it returns nil, the config channel will be active and return log // messages until it runs out or the context is canceled. func (daemon *Daemon) ContainerLogs(ctx context.Context, containerName string, config *types.ContainerLogsOptions) (messages <-chan *backend.LogMessage, isTTY bool, retErr error) { - lg := log.G(ctx).WithFields(logrus.Fields{ + lg := log.G(ctx).WithFields(log.Fields{ "module": "daemon", "method": "(*Daemon).ContainerLogs", "container": containerName, diff --git a/daemon/monitor.go b/daemon/monitor.go index ff48e55b5b..d8ed3417a9 100644 --- a/daemon/monitor.go +++ b/daemon/monitor.go @@ -13,7 +13,6 @@ import ( libcontainerdtypes "github.com/docker/docker/libcontainerd/types" "github.com/docker/docker/restartmanager" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) func (daemon *Daemon) setStateCounter(c *container.Container) { @@ -43,9 +42,9 @@ func (daemon *Daemon) handleContainerExit(c *container.Container, e *libcontaine es, err := tsk.Delete(ctx) cancel() if err != nil { - log.G(ctx).WithFields(logrus.Fields{ - logrus.ErrorKey: err, - "container": c.ID, + log.G(ctx).WithFields(log.Fields{ + "error": err, + "container": c.ID, }).Warn("failed to delete container from containerd") } else { exitStatus = container.ExitStatus{ @@ -73,8 +72,8 @@ func (daemon *Daemon) handleContainerExit(c *container.Container, e *libcontaine execDuration := time.Since(c.StartedAt) restart, wait, err := c.RestartManager().ShouldRestart(uint32(exitStatus.ExitCode), daemonShutdown || c.HasBeenManuallyStopped, execDuration) if err != nil { - log.G(ctx).WithFields(logrus.Fields{ - logrus.ErrorKey: err, + log.G(ctx).WithFields(log.Fields{ + "error": err, "container": c.ID, "restartCount": c.RestartCount, "exitStatus": exitStatus, @@ -93,7 +92,7 @@ func (daemon *Daemon) handleContainerExit(c *container.Container, e *libcontaine if restart { c.RestartCount++ - log.G(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithFields(log.Fields{ "container": c.ID, "restartCount": c.RestartCount, "exitStatus": exitStatus, @@ -207,10 +206,10 @@ func (daemon *Daemon) ProcessEvent(id string, e libcontainerdtypes.EventType, ei if execConfig.Process != nil { go func() { if _, err := execConfig.Process.Delete(context.Background()); err != nil { - log.G(ctx).WithFields(logrus.Fields{ - logrus.ErrorKey: err, - "container": ei.ContainerID, - "process": ei.ProcessID, + log.G(ctx).WithFields(log.Fields{ + "error": err, + "container": ei.ContainerID, + "process": ei.ProcessID, }).Warn("failed to delete process") } }() @@ -232,9 +231,9 @@ func (daemon *Daemon) ProcessEvent(id string, e libcontainerdtypes.EventType, ei if errdefs.IsNotFound(err) { // The container was started by not-docker and so could have been deleted by // not-docker before we got around to loading it from containerd. - log.G(context.TODO()).WithFields(logrus.Fields{ - logrus.ErrorKey: err, - "container": c.ID, + log.G(context.TODO()).WithFields(log.Fields{ + "error": err, + "container": c.ID, }).Debug("could not load containerd container for start event") return nil } @@ -243,9 +242,9 @@ func (daemon *Daemon) ProcessEvent(id string, e libcontainerdtypes.EventType, ei tsk, err := ctr.Task(context.Background()) if err != nil { if errdefs.IsNotFound(err) { - log.G(context.TODO()).WithFields(logrus.Fields{ - logrus.ErrorKey: err, - "container": c.ID, + log.G(context.TODO()).WithFields(log.Fields{ + "error": err, + "container": c.ID, }).Debug("failed to load task for externally-started container") return nil } @@ -311,5 +310,5 @@ func (daemon *Daemon) autoRemove(cfg *config.Config, c *container.Container) { return } - log.G(context.TODO()).WithFields(logrus.Fields{logrus.ErrorKey: err, "container": c.ID}).Error("error removing container") + log.G(context.TODO()).WithFields(log.Fields{"error": err, "container": c.ID}).Error("error removing container") } diff --git a/daemon/mounts.go b/daemon/mounts.go index 6a4d22cc09..b562fa50ea 100644 --- a/daemon/mounts.go +++ b/daemon/mounts.go @@ -9,7 +9,6 @@ import ( mounttypes "github.com/docker/docker/api/types/mount" "github.com/docker/docker/container" volumesservice "github.com/docker/docker/volume/service" - "github.com/sirupsen/logrus" ) func (daemon *Daemon) prepareMountPoints(container *container.Container) error { @@ -23,7 +22,7 @@ func (daemon *Daemon) prepareMountPoints(container *container.Container) error { continue } if alive { - log.G(context.TODO()).WithFields(logrus.Fields{ + log.G(context.TODO()).WithFields(log.Fields{ "container": container.ID, "volume": config.Volume.Name(), }).Debug("Live-restoring volume for alive container") diff --git a/daemon/network.go b/daemon/network.go index e78f7654f2..5b9c57226a 100644 --- a/daemon/network.go +++ b/daemon/network.go @@ -32,7 +32,6 @@ import ( "github.com/docker/docker/runconfig" "github.com/docker/go-connections/nat" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) // PredefinedNetworkError is returned when user tries to create predefined network that already exists. @@ -328,7 +327,7 @@ func (daemon *Daemon) createNetwork(cfg *config.Config, create types.NetworkCrea if defaultOpts, ok := cfg.DefaultNetworkOpts[driver]; create.ConfigFrom == nil && ok { for k, v := range defaultOpts { if _, ok := networkOptions[k]; !ok { - log.G(context.TODO()).WithFields(logrus.Fields{"driver": driver, "network": id, k: v}).Debug("Applying network default option") + log.G(context.TODO()).WithFields(log.Fields{"driver": driver, "network": id, k: v}).Debug("Applying network default option") networkOptions[k] = v } } @@ -412,7 +411,7 @@ func (daemon *Daemon) pluginRefCount(driver, capability string, mode int) { if daemon.PluginStore != nil { _, err := daemon.PluginStore.Get(driver, capability, mode) if err != nil { - log.G(context.TODO()).WithError(err).WithFields(logrus.Fields{"mode": mode, "driver": driver}).Error("Error handling plugin refcount operation") + log.G(context.TODO()).WithError(err).WithFields(log.Fields{"mode": mode, "driver": driver}).Error("Error handling plugin refcount operation") } } } diff --git a/daemon/reload.go b/daemon/reload.go index ff1f076670..1e79515f0e 100644 --- a/daemon/reload.go +++ b/daemon/reload.go @@ -9,7 +9,6 @@ import ( "github.com/containerd/containerd/log" "github.com/hashicorp/go-multierror" "github.com/mitchellh/copystructure" - "github.com/sirupsen/logrus" "github.com/docker/docker/daemon/config" ) @@ -280,7 +279,7 @@ func (daemon *Daemon) reloadNetworkDiagnosticPort(txn *reloadTxn, newCfg *config return nil } // Enable the network diagnostic if the flag is set with a valid port within the range - log.G(context.TODO()).WithFields(logrus.Fields{"port": conf.NetworkDiagnosticPort, "ip": "127.0.0.1"}).Warn("Starting network diagnostic server") + log.G(context.TODO()).WithFields(log.Fields{"port": conf.NetworkDiagnosticPort, "ip": "127.0.0.1"}).Warn("Starting network diagnostic server") daemon.netController.StartDiagnostic(conf.NetworkDiagnosticPort) return nil }) diff --git a/distribution/pull_v2.go b/distribution/pull_v2.go index 82d686db2c..17ba118395 100644 --- a/distribution/pull_v2.go +++ b/distribution/pull_v2.go @@ -33,7 +33,6 @@ import ( "github.com/opencontainers/go-digest" ocispec "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" - "github.com/sirupsen/logrus" archvariant "github.com/tonistiigi/go-archvariant" ) @@ -375,11 +374,10 @@ func (p *puller) pullTag(ctx context.Context, ref reference.Named, platform *oci return false, fmt.Errorf("internal error: reference has neither a tag nor a digest: %s", reference.FamiliarString(ref)) } - ctx = log.WithLogger(ctx, log.G(ctx).WithFields( - logrus.Fields{ - "digest": dgst, - "remote": ref, - })) + ctx = log.WithLogger(ctx, log.G(ctx).WithFields(log.Fields{ + "digest": dgst, + "remote": ref, + })) desc := ocispec.Descriptor{ MediaType: mt, diff --git a/image/store.go b/image/store.go index 55d43c354a..6be74e671a 100644 --- a/image/store.go +++ b/image/store.go @@ -13,7 +13,6 @@ import ( "github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest/digestset" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) // Store is an interface for creating and accessing images @@ -75,7 +74,7 @@ func (is *store) restore() error { // if we don't need it. The "f" type alias is here is just for convenience, // and to make the code _slightly_ more DRY. See the discussion on GitHub; // https://github.com/moby/moby/pull/44426#discussion_r1059519071 - type f = logrus.Fields + type f = log.Fields err := is.fs.Walk(func(dgst digest.Digest) error { img, err := is.Get(ID(dgst)) if err != nil { diff --git a/integration-cli/docker_cli_logs_test.go b/integration-cli/docker_cli_logs_test.go index cca5c9438e..a963686aec 100644 --- a/integration-cli/docker_cli_logs_test.go +++ b/integration-cli/docker_cli_logs_test.go @@ -9,8 +9,8 @@ import ( "testing" "time" + "github.com/containerd/containerd/log" "github.com/docker/docker/integration-cli/cli" - "github.com/docker/docker/pkg/jsonmessage" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) @@ -67,7 +67,7 @@ func (s *DockerCLILogsSuite) TestLogsTimestamps(c *testing.T) { for _, l := range lines { if l != "" { - _, err := time.Parse(jsonmessage.RFC3339NanoFixed+" ", ts.FindString(l)) + _, err := time.Parse(log.RFC3339NanoFixed+" ", ts.FindString(l)) assert.NilError(c, err, "Failed to parse timestamp from %v", l) // ensure we have padded 0's assert.Equal(c, l[29], uint8('Z')) diff --git a/libcontainerd/local/local_windows.go b/libcontainerd/local/local_windows.go index 5d883f1c79..6cb577f4ba 100644 --- a/libcontainerd/local/local_windows.go +++ b/libcontainerd/local/local_windows.go @@ -163,13 +163,13 @@ func (c *client) NewContainer(_ context.Context, id string, spec *specs.Spec, sh ei := libcontainerdtypes.EventInfo{ ContainerID: id, } - c.logger.WithFields(logrus.Fields{ + c.logger.WithFields(log.Fields{ "container": id, "event": libcontainerdtypes.EventCreate, }).Info("sending event") err := c.backend.ProcessEvent(id, libcontainerdtypes.EventCreate, ei) if err != nil { - c.logger.WithError(err).WithFields(logrus.Fields{ + c.logger.WithError(err).WithFields(log.Fields{ "container": id, "event": libcontainerdtypes.EventCreate, }).Error("failed to process event") @@ -498,14 +498,14 @@ func (ctr *container) Start(_ context.Context, _ string, withStdin bool, attachS ProcessID: t.id, Pid: pid, } - ctr.client.logger.WithFields(logrus.Fields{ + ctr.client.logger.WithFields(log.Fields{ "container": ctr.id, "event": libcontainerdtypes.EventStart, "event-info": ei, }).Info("sending event") err := ctr.client.backend.ProcessEvent(ei.ContainerID, libcontainerdtypes.EventStart, ei) if err != nil { - ctr.client.logger.WithError(err).WithFields(logrus.Fields{ + ctr.client.logger.WithError(err).WithFields(log.Fields{ "container": ei.ContainerID, "event": libcontainerdtypes.EventStart, "event-info": ei, @@ -562,7 +562,7 @@ func (t *task) Exec(ctx context.Context, processID string, spec *specs.Process, if err != nil { return nil, err } - logger := t.ctr.client.logger.WithFields(logrus.Fields{ + logger := t.ctr.client.logger.WithFields(log.Fields{ "container": t.ctr.id, "exec": processID, }) @@ -654,14 +654,14 @@ func (t *task) Exec(ctx context.Context, processID string, spec *specs.Process, ProcessID: p.id, Pid: uint32(pid), } - t.ctr.client.logger.WithFields(logrus.Fields{ + t.ctr.client.logger.WithFields(log.Fields{ "container": t.ctr.id, "event": libcontainerdtypes.EventExecAdded, "event-info": ei, }).Info("sending event") err := t.ctr.client.backend.ProcessEvent(t.ctr.id, libcontainerdtypes.EventExecAdded, ei) if err != nil { - t.ctr.client.logger.WithError(err).WithFields(logrus.Fields{ + t.ctr.client.logger.WithError(err).WithFields(log.Fields{ "container": t.ctr.id, "event": libcontainerdtypes.EventExecAdded, "event-info": ei, @@ -669,7 +669,7 @@ func (t *task) Exec(ctx context.Context, processID string, spec *specs.Process, } err = t.ctr.client.backend.ProcessEvent(t.ctr.id, libcontainerdtypes.EventExecStarted, ei) if err != nil { - t.ctr.client.logger.WithError(err).WithFields(logrus.Fields{ + t.ctr.client.logger.WithError(err).WithFields(log.Fields{ "container": t.ctr.id, "event": libcontainerdtypes.EventExecStarted, "event-info": ei, @@ -709,7 +709,7 @@ func (t *task) Kill(_ context.Context, signal syscall.Signal) error { return err } - logger := t.ctr.client.logger.WithFields(logrus.Fields{ + logger := t.ctr.client.logger.WithFields(log.Fields{ "container": t.ctr.id, "process": t.id, "pid": t.Pid(), @@ -748,7 +748,7 @@ func (p *process) Resize(_ context.Context, width, height uint32) error { return errors.WithStack(errdefs.NotFound(errors.New("process not found"))) } - p.ctr.client.logger.WithFields(logrus.Fields{ + p.ctr.client.logger.WithFields(log.Fields{ "container": p.ctr.id, "process": p.id, "height": height, @@ -795,12 +795,12 @@ func (t *task) Pause(_ context.Context) error { ContainerID: t.ctr.id, ProcessID: t.id, }) - t.ctr.client.logger.WithFields(logrus.Fields{ + t.ctr.client.logger.WithFields(log.Fields{ "container": t.ctr.id, "event": libcontainerdtypes.EventPaused, }).Info("sending event") if err != nil { - t.ctr.client.logger.WithError(err).WithFields(logrus.Fields{ + t.ctr.client.logger.WithError(err).WithFields(log.Fields{ "container": t.ctr.id, "event": libcontainerdtypes.EventPaused, }).Error("failed to process event") @@ -836,12 +836,12 @@ func (t *task) Resume(ctx context.Context) error { ContainerID: t.ctr.id, ProcessID: t.id, }) - t.ctr.client.logger.WithFields(logrus.Fields{ + t.ctr.client.logger.WithFields(log.Fields{ "container": t.ctr.id, "event": libcontainerdtypes.EventResumed, }).Info("sending event") if err != nil { - t.ctr.client.logger.WithError(err).WithFields(logrus.Fields{ + t.ctr.client.logger.WithError(err).WithFields(log.Fields{ "container": t.ctr.id, "event": libcontainerdtypes.EventResumed, }).Error("failed to process event") @@ -1109,7 +1109,7 @@ func (ctr *container) terminateContainer() error { } func (p *process) reap() { - logger := p.ctr.client.logger.WithFields(logrus.Fields{ + logger := p.ctr.client.logger.WithFields(log.Fields{ "container": p.ctr.id, "process": p.id, }) @@ -1166,14 +1166,14 @@ func (p *process) reap() { ExitedAt: exitedAt, Error: eventErr, } - p.ctr.client.logger.WithFields(logrus.Fields{ + p.ctr.client.logger.WithFields(log.Fields{ "container": p.ctr.id, "event": libcontainerdtypes.EventExit, "event-info": ei, }).Info("sending event") err := p.ctr.client.backend.ProcessEvent(p.ctr.id, libcontainerdtypes.EventExit, ei) if err != nil { - p.ctr.client.logger.WithError(err).WithFields(logrus.Fields{ + p.ctr.client.logger.WithError(err).WithFields(log.Fields{ "container": p.ctr.id, "event": libcontainerdtypes.EventExit, "event-info": ei, @@ -1200,7 +1200,7 @@ func (ctr *container) Delete(context.Context) error { } var ( - logger = ctr.client.logger.WithFields(logrus.Fields{ + logger = ctr.client.logger.WithFields(log.Fields{ "container": ctr.id, }) thisErr error diff --git a/libcontainerd/remote/client.go b/libcontainerd/remote/client.go index cd5cf89dd0..71684ddea2 100644 --- a/libcontainerd/remote/client.go +++ b/libcontainerd/remote/client.go @@ -167,7 +167,7 @@ func (c *container) Start(ctx context.Context, checkpointDir string, withStdin b if checkpoint != nil { err := c.client.client.ContentStore().Delete(ctx, checkpoint.Digest) if err != nil { - c.client.logger.WithError(err).WithFields(logrus.Fields{ + c.client.logger.WithError(err).WithFields(log.Fields{ "ref": checkpointDir, "digest": checkpoint.Digest, }).Warnf("failed to delete temporary checkpoint entry") @@ -392,7 +392,7 @@ func (c *container) Delete(ctx context.Context) error { } if os.Getenv("LIBCONTAINERD_NOCLEAN") != "1" { if err := os.RemoveAll(bundle); err != nil { - c.client.logger.WithContext(ctx).WithError(err).WithFields(logrus.Fields{ + c.client.logger.WithContext(ctx).WithError(err).WithFields(log.Fields{ "container": c.c8dCtr.ID(), "bundle": bundle, }).Error("failed to remove state dir") @@ -573,7 +573,7 @@ func (c *client) processEvent(ctx context.Context, et libcontainerdtypes.EventTy c.eventQ.Append(ei.ContainerID, func() { err := c.backend.ProcessEvent(ei.ContainerID, et, ei) if err != nil { - c.logger.WithContext(ctx).WithError(err).WithFields(logrus.Fields{ + c.logger.WithContext(ctx).WithError(err).WithFields(log.Fields{ "container": ei.ContainerID, "event": et, "event-info": ei, @@ -718,7 +718,7 @@ func (c *client) processEventStream(ctx context.Context, ns string) { ContainerID: t.ContainerID, } case *apievents.TaskDelete: - c.logger.WithFields(logrus.Fields{ + c.logger.WithFields(log.Fields{ "topic": ev.Topic, "type": reflect.TypeOf(t), "container": t.ContainerID, @@ -726,7 +726,7 @@ func (c *client) processEventStream(ctx context.Context, ns string) { ).Info("ignoring event") continue default: - c.logger.WithFields(logrus.Fields{ + c.logger.WithFields(log.Fields{ "topic": ev.Topic, "type": reflect.TypeOf(t), }, diff --git a/libcontainerd/remote/client_io_windows.go b/libcontainerd/remote/client_io_windows.go index 5bb8e68ba7..eb9af2f3aa 100644 --- a/libcontainerd/remote/client_io_windows.go +++ b/libcontainerd/remote/client_io_windows.go @@ -7,8 +7,8 @@ import ( winio "github.com/Microsoft/go-winio" "github.com/containerd/containerd/cio" + "github.com/containerd/containerd/log" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) type delayedConnection struct { @@ -59,7 +59,7 @@ type stdioPipes struct { func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) { p := &stdioPipes{} if fifos.Stdin != "" { - c.logger.WithFields(logrus.Fields{"stdin": fifos.Stdin}).Debug("listen") + c.logger.WithField("stdin", fifos.Stdin).Debug("listen") l, err := winio.ListenPipe(fifos.Stdin, nil) if err != nil { return nil, errors.Wrapf(err, "failed to create stdin pipe %s", fifos.Stdin) @@ -76,7 +76,7 @@ func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) { p.stdin = dc go func() { - c.logger.WithFields(logrus.Fields{"stdin": fifos.Stdin}).Debug("accept") + c.logger.WithField("stdin", fifos.Stdin).Debug("accept") conn, err := l.Accept() if err != nil { dc.Close() @@ -85,14 +85,14 @@ func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) { } return } - c.logger.WithFields(logrus.Fields{"stdin": fifos.Stdin}).Debug("connected") + c.logger.WithField("stdin", fifos.Stdin).Debug("connected") dc.con = conn dc.unblockConnectionWaiters() }() } if fifos.Stdout != "" { - c.logger.WithFields(logrus.Fields{"stdout": fifos.Stdout}).Debug("listen") + c.logger.WithField("stdout", fifos.Stdout).Debug("listen") l, err := winio.ListenPipe(fifos.Stdout, nil) if err != nil { return nil, errors.Wrapf(err, "failed to create stdout pipe %s", fifos.Stdout) @@ -109,23 +109,23 @@ func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) { p.stdout = dc go func() { - c.logger.WithFields(logrus.Fields{"stdout": fifos.Stdout}).Debug("accept") + c.logger.WithField("stdout", fifos.Stdout).Debug("accept") conn, err := l.Accept() if err != nil { dc.Close() if err != winio.ErrPipeListenerClosed { - c.logger.WithError(err).Errorf("failed to accept stdout connection on %s", fifos.Stdout) + c.logger.WithFields(log.Fields{"error": err, "stdout": fifos.Stdout}).Error("failed to accept stdout connection") } return } - c.logger.WithFields(logrus.Fields{"stdout": fifos.Stdout}).Debug("connected") + c.logger.WithField("stdout", fifos.Stdout).Debug("connected") dc.con = conn dc.unblockConnectionWaiters() }() } if fifos.Stderr != "" { - c.logger.WithFields(logrus.Fields{"stderr": fifos.Stderr}).Debug("listen") + c.logger.WithField("stderr", fifos.Stderr).Debug("listen") l, err := winio.ListenPipe(fifos.Stderr, nil) if err != nil { return nil, errors.Wrapf(err, "failed to create stderr pipe %s", fifos.Stderr) @@ -142,7 +142,7 @@ func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) { p.stderr = dc go func() { - c.logger.WithFields(logrus.Fields{"stderr": fifos.Stderr}).Debug("accept") + c.logger.WithField("stderr", fifos.Stderr).Debug("accept") conn, err := l.Accept() if err != nil { dc.Close() @@ -151,7 +151,7 @@ func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) { } return } - c.logger.WithFields(logrus.Fields{"stderr": fifos.Stderr}).Debug("connected") + c.logger.WithField("stderr", fifos.Stderr).Debug("connected") dc.con = conn dc.unblockConnectionWaiters() }() diff --git a/libnetwork/cmd/diagnostic/main.go b/libnetwork/cmd/diagnostic/main.go index 6ad668fefd..cdd2c00121 100644 --- a/libnetwork/cmd/diagnostic/main.go +++ b/libnetwork/cmd/diagnostic/main.go @@ -12,8 +12,6 @@ import ( "os" "strings" - "github.com/sirupsen/logrus" - "github.com/containerd/containerd/log" "github.com/docker/docker/libnetwork" "github.com/docker/docker/libnetwork/diagnostic" @@ -53,7 +51,7 @@ func main() { flag.Parse() if *verbosePtr { - logrus.SetLevel(logrus.DebugLevel) + _ = log.SetLevel("debug") } if _, ok := os.LookupEnv("DIND_CLIENT"); !ok && *joinPtr { diff --git a/libnetwork/cmd/networkdb-test/testMain.go b/libnetwork/cmd/networkdb-test/testMain.go index 6ddfa1336d..f2ef347a3c 100644 --- a/libnetwork/cmd/networkdb-test/testMain.go +++ b/libnetwork/cmd/networkdb-test/testMain.go @@ -4,18 +4,13 @@ import ( "context" "os" - "github.com/sirupsen/logrus" - "github.com/containerd/containerd/log" "github.com/docker/docker/libnetwork/cmd/networkdb-test/dbclient" "github.com/docker/docker/libnetwork/cmd/networkdb-test/dbserver" ) func main() { - formatter := &logrus.TextFormatter{ - FullTimestamp: true, - } - logrus.SetFormatter(formatter) + _ = log.SetFormat(log.TextFormat) log.G(context.TODO()).Infof("Starting the image with these args: %v", os.Args) if len(os.Args) < 1 { log.G(context.TODO()).Fatal("You need at least 1 argument [client/server]") diff --git a/libnetwork/diagnostic/server.go b/libnetwork/diagnostic/server.go index efeb15c17f..42bf37459f 100644 --- a/libnetwork/diagnostic/server.go +++ b/libnetwork/diagnostic/server.go @@ -14,7 +14,6 @@ import ( "github.com/containerd/containerd/log" "github.com/docker/docker/libnetwork/internal/caller" "github.com/docker/docker/pkg/stack" - "github.com/sirupsen/logrus" ) // HTTPHandlerFunc TODO @@ -130,24 +129,32 @@ func (s *Server) IsDiagnosticEnabled() bool { } func notImplemented(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() //nolint:errcheck - _, json := ParseHTTPFormOptions(r) + _ = r.ParseForm() + _, jsonOutput := ParseHTTPFormOptions(r) rsp := WrongCommand("not implemented", fmt.Sprintf("URL path: %s no method implemented check /help\n", r.URL.Path)) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("command not implemented done") + log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }).Info("command not implemented done") - HTTPReply(w, rsp, json) //nolint:errcheck + _, _ = HTTPReply(w, rsp, jsonOutput) } func help(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() //nolint:errcheck - _, json := ParseHTTPFormOptions(r) + _ = r.ParseForm() + _, jsonOutput := ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("help done") + log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }).Info("help done") n, ok := ctx.(*Server) var result string @@ -155,35 +162,39 @@ func help(ctx interface{}, w http.ResponseWriter, r *http.Request) { for path := range n.registeredHanders { result += fmt.Sprintf("%s\n", path) } - HTTPReply(w, CommandSucceed(&StringCmd{Info: result}), json) //nolint:errcheck + _, _ = HTTPReply(w, CommandSucceed(&StringCmd{Info: result}), jsonOutput) } } func ready(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() //nolint:errcheck - _, json := ParseHTTPFormOptions(r) + _ = r.ParseForm() + _, jsonOutput := ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("ready done") - HTTPReply(w, CommandSucceed(&StringCmd{Info: "OK"}), json) //nolint:errcheck + log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }).Info("ready done") + _, _ = HTTPReply(w, CommandSucceed(&StringCmd{Info: "OK"}), jsonOutput) } func stackTrace(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() //nolint:errcheck - _, json := ParseHTTPFormOptions(r) + _ = r.ParseForm() + _, jsonOutput := ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("stack trace") + logger := log.G(context.TODO()).WithFields(log.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) + logger.Info("stack trace") path, err := stack.DumpToFile("/tmp/") if err != nil { - log.WithError(err).Error("failed to write goroutines dump") - HTTPReply(w, FailCommand(err), json) //nolint:errcheck + logger.WithError(err).Error("failed to write goroutines dump") + _, _ = HTTPReply(w, FailCommand(err), jsonOutput) } else { - log.Info("stack trace done") - HTTPReply(w, CommandSucceed(&StringCmd{Info: fmt.Sprintf("goroutine stacks written to %s", path)}), json) //nolint:errcheck + logger.Info("stack trace done") + _, _ = HTTPReply(w, CommandSucceed(&StringCmd{Info: "goroutine stacks written to " + path}), jsonOutput) } } @@ -203,12 +214,12 @@ type JSONOutput struct { // ParseHTTPFormOptions easily parse the JSON printing options func ParseHTTPFormOptions(r *http.Request) (bool, *JSONOutput) { _, unsafe := r.Form["unsafe"] - v, json := r.Form["json"] + v, enableJSON := r.Form["json"] var pretty bool if len(v) > 0 { pretty = v[0] == "pretty" } - return unsafe, &JSONOutput{enable: json, prettyPrint: pretty} + return unsafe, &JSONOutput{enable: enableJSON, prettyPrint: pretty} } // HTTPReply helper function that takes care of sending the message out diff --git a/libnetwork/drivers/overlay/ov_network.go b/libnetwork/drivers/overlay/ov_network.go index 8b712808b4..0b80905e43 100644 --- a/libnetwork/drivers/overlay/ov_network.go +++ b/libnetwork/drivers/overlay/ov_network.go @@ -22,7 +22,6 @@ import ( "github.com/docker/docker/libnetwork/osl" "github.com/docker/docker/libnetwork/types" "github.com/hashicorp/go-multierror" - "github.com/sirupsen/logrus" "github.com/vishvananda/netlink" "github.com/vishvananda/netns" "golang.org/x/sys/unix" @@ -217,17 +216,17 @@ func (d *driver) DeleteNetwork(nid string) error { if n.secure { for _, s := range n.subnets { if err := programMangle(s.vni, false); err != nil { - log.G(context.TODO()).WithFields(logrus.Fields{ - logrus.ErrorKey: err, - "network_id": n.id, - "subnet": s.subnetIP, + log.G(context.TODO()).WithFields(log.Fields{ + "error": err, + "network_id": n.id, + "subnet": s.subnetIP, }).Warn("Failed to clean up iptables rules during overlay network deletion") } if err := programInput(s.vni, false); err != nil { - log.G(context.TODO()).WithFields(logrus.Fields{ - logrus.ErrorKey: err, - "network_id": n.id, - "subnet": s.subnetIP, + log.G(context.TODO()).WithFields(log.Fields{ + "error": err, + "network_id": n.id, + "subnet": s.subnetIP, }).Warn("Failed to clean up iptables rules during overlay network deletion") } } diff --git a/libnetwork/networkdb/networkdb_test.go b/libnetwork/networkdb/networkdb_test.go index 19969210bc..9811428a07 100644 --- a/libnetwork/networkdb/networkdb_test.go +++ b/libnetwork/networkdb/networkdb_test.go @@ -14,7 +14,6 @@ import ( "github.com/docker/docker/pkg/stringid" "github.com/docker/go-events" "github.com/hashicorp/memberlist" - "github.com/sirupsen/logrus" "gotest.tools/v3/assert" is "gotest.tools/v3/assert/cmp" "gotest.tools/v3/poll" @@ -24,7 +23,7 @@ var dbPort int32 = 10000 func TestMain(m *testing.M) { os.WriteFile("/proc/sys/net/ipv6/conf/lo/disable_ipv6", []byte{'0', '\n'}, 0o644) - logrus.SetLevel(logrus.ErrorLevel) + log.SetLevel("error") os.Exit(m.Run()) } @@ -840,7 +839,7 @@ func TestNetworkDBIslands(t *testing.T) { return defaultTimeout } - logrus.SetLevel(logrus.DebugLevel) + _ = log.SetLevel("debug") conf := DefaultConfig() // Shorten durations to speed up test execution. conf.rejoinClusterDuration = conf.rejoinClusterDuration / 10 diff --git a/libnetwork/networkdb/networkdbdiagnostic.go b/libnetwork/networkdb/networkdbdiagnostic.go index 5d59a3f36e..3ddfa78cc9 100644 --- a/libnetwork/networkdb/networkdbdiagnostic.go +++ b/libnetwork/networkdb/networkdbdiagnostic.go @@ -10,7 +10,6 @@ import ( "github.com/containerd/containerd/log" "github.com/docker/docker/libnetwork/diagnostic" "github.com/docker/docker/libnetwork/internal/caller" - "github.com/sirupsen/logrus" ) const ( @@ -34,17 +33,22 @@ var NetDbPaths2Func = map[string]diagnostic.HTTPHandlerFunc{ } func dbJoin(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() + _ = r.ParseForm() diagnostic.DebugHTTPForm(r) _, json := diagnostic.ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("join cluster") + logger := log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }) + logger.Info("join cluster") if len(r.Form["members"]) < 1 { rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?members=ip1,ip2,...", r.URL.Path)) - log.Error("join cluster failed, wrong input") + logger.Error("join cluster failed, wrong input") diagnostic.HTTPReply(w, rsp, json) return } @@ -54,12 +58,12 @@ func dbJoin(ctx interface{}, w http.ResponseWriter, r *http.Request) { err := nDB.Join(strings.Split(r.Form["members"][0], ",")) if err != nil { rsp := diagnostic.FailCommand(fmt.Errorf("%s error in the DB join %s", r.URL.Path, err)) - log.WithError(err).Error("join cluster failed") + logger.WithError(err).Error("join cluster failed") diagnostic.HTTPReply(w, rsp, json) return } - log.Info("join cluster done") + logger.Info("join cluster done") diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) return } @@ -67,17 +71,22 @@ func dbJoin(ctx interface{}, w http.ResponseWriter, r *http.Request) { } func dbPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() + _ = r.ParseForm() diagnostic.DebugHTTPForm(r) _, json := diagnostic.ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("network peers") + logger := log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }) + logger.Info("network peers") if len(r.Form["nid"]) < 1 { rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=test", r.URL.Path)) - log.Error("network peers failed, wrong input") + logger.Error("network peers failed, wrong input") diagnostic.HTTPReply(w, rsp, json) return } @@ -93,7 +102,7 @@ func dbPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) { rsp.Elements = append(rsp.Elements, &diagnostic.PeerEntryObj{Index: i, Name: peerInfo.Name, IP: peerInfo.IP}) } } - log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("network peers done") + logger.WithField("response", fmt.Sprintf("%+v", rsp)).Info("network peers done") diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json) return } @@ -101,13 +110,18 @@ func dbPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) { } func dbClusterPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() + _ = r.ParseForm() diagnostic.DebugHTTPForm(r) _, json := diagnostic.ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("cluster peers") + logger := log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }) + logger.Info("cluster peers") nDB, ok := ctx.(*NetworkDB) if ok { @@ -116,7 +130,7 @@ func dbClusterPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) { for i, peerInfo := range peers { rsp.Elements = append(rsp.Elements, &diagnostic.PeerEntryObj{Index: i, Name: peerInfo.Name, IP: peerInfo.IP}) } - log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("cluster peers done") + logger.WithField("response", fmt.Sprintf("%+v", rsp)).Info("cluster peers done") diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json) return } @@ -124,20 +138,25 @@ func dbClusterPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) { } func dbCreateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() + _ = r.ParseForm() diagnostic.DebugHTTPForm(r) unsafe, json := diagnostic.ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("create entry") + logger := log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }) + logger.Info("create entry") if len(r.Form["tname"]) < 1 || len(r.Form["nid"]) < 1 || len(r.Form["key"]) < 1 || len(r.Form["value"]) < 1 { rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k&value=v", r.URL.Path)) - log.Error("create entry failed, wrong input") + logger.Error("create entry failed, wrong input") diagnostic.HTTPReply(w, rsp, json) return } @@ -151,7 +170,7 @@ func dbCreateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { var err error decodedValue, err = base64.StdEncoding.DecodeString(value) if err != nil { - log.WithError(err).Error("create entry failed") + logger.WithError(err).Error("create entry failed") diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) return } @@ -162,10 +181,10 @@ func dbCreateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { if err := nDB.CreateEntry(tname, nid, key, decodedValue); err != nil { rsp := diagnostic.FailCommand(err) diagnostic.HTTPReply(w, rsp, json) - log.WithError(err).Error("create entry failed") + logger.WithError(err).Error("create entry failed") return } - log.Info("create entry done") + logger.Info("create entry done") diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) return } @@ -173,20 +192,25 @@ func dbCreateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { } func dbUpdateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() + _ = r.ParseForm() diagnostic.DebugHTTPForm(r) unsafe, json := diagnostic.ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("update entry") + logger := log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }) + logger.Info("update entry") if len(r.Form["tname"]) < 1 || len(r.Form["nid"]) < 1 || len(r.Form["key"]) < 1 || len(r.Form["value"]) < 1 { rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k&value=v", r.URL.Path)) - log.Error("update entry failed, wrong input") + logger.Error("update entry failed, wrong input") diagnostic.HTTPReply(w, rsp, json) return } @@ -200,7 +224,7 @@ func dbUpdateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { var err error decodedValue, err = base64.StdEncoding.DecodeString(value) if err != nil { - log.WithError(err).Error("update entry failed") + logger.WithError(err).Error("update entry failed") diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) return } @@ -209,11 +233,11 @@ func dbUpdateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { nDB, ok := ctx.(*NetworkDB) if ok { if err := nDB.UpdateEntry(tname, nid, key, decodedValue); err != nil { - log.WithError(err).Error("update entry failed") + logger.WithError(err).Error("update entry failed") diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) return } - log.Info("update entry done") + logger.Info("update entry done") diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) return } @@ -221,19 +245,24 @@ func dbUpdateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { } func dbDeleteEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() + _ = r.ParseForm() diagnostic.DebugHTTPForm(r) _, json := diagnostic.ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("delete entry") + logger := log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }) + logger.Info("delete entry") if len(r.Form["tname"]) < 1 || len(r.Form["nid"]) < 1 || len(r.Form["key"]) < 1 { rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k", r.URL.Path)) - log.Error("delete entry failed, wrong input") + logger.Error("delete entry failed, wrong input") diagnostic.HTTPReply(w, rsp, json) return } @@ -246,11 +275,11 @@ func dbDeleteEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { if ok { err := nDB.DeleteEntry(tname, nid, key) if err != nil { - log.WithError(err).Error("delete entry failed") + logger.WithError(err).Error("delete entry failed") diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) return } - log.Info("delete entry done") + logger.Info("delete entry done") diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) return } @@ -258,19 +287,24 @@ func dbDeleteEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { } func dbGetEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() + _ = r.ParseForm() diagnostic.DebugHTTPForm(r) unsafe, json := diagnostic.ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("get entry") + logger := log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }) + logger.Info("get entry") if len(r.Form["tname"]) < 1 || len(r.Form["nid"]) < 1 || len(r.Form["key"]) < 1 { rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k", r.URL.Path)) - log.Error("get entry failed, wrong input") + logger.Error("get entry failed, wrong input") diagnostic.HTTPReply(w, rsp, json) return } @@ -283,7 +317,7 @@ func dbGetEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { if ok { value, err := nDB.GetEntry(tname, nid, key) if err != nil { - log.WithError(err).Error("get entry failed") + logger.WithError(err).Error("get entry failed") diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) return } @@ -296,7 +330,7 @@ func dbGetEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { } rsp := &diagnostic.TableEntryObj{Key: key, Value: encodedValue} - log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("get entry done") + logger.WithField("response", fmt.Sprintf("%+v", rsp)).Info("get entry done") diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json) return } @@ -304,17 +338,22 @@ func dbGetEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { } func dbJoinNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() + _ = r.ParseForm() diagnostic.DebugHTTPForm(r) _, json := diagnostic.ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("join network") + logger := log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }) + logger.Info("join network") if len(r.Form["nid"]) < 1 { rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=network_id", r.URL.Path)) - log.Error("join network failed, wrong input") + logger.Error("join network failed, wrong input") diagnostic.HTTPReply(w, rsp, json) return } @@ -324,11 +363,11 @@ func dbJoinNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) { nDB, ok := ctx.(*NetworkDB) if ok { if err := nDB.JoinNetwork(nid); err != nil { - log.WithError(err).Error("join network failed") + logger.WithError(err).Error("join network failed") diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) return } - log.Info("join network done") + logger.Info("join network done") diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) return } @@ -336,17 +375,22 @@ func dbJoinNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) { } func dbLeaveNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() + _ = r.ParseForm() diagnostic.DebugHTTPForm(r) _, json := diagnostic.ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("leave network") + logger := log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }) + logger.Info("leave network") if len(r.Form["nid"]) < 1 { rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=network_id", r.URL.Path)) - log.Error("leave network failed, wrong input") + logger.Error("leave network failed, wrong input") diagnostic.HTTPReply(w, rsp, json) return } @@ -356,11 +400,11 @@ func dbLeaveNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) { nDB, ok := ctx.(*NetworkDB) if ok { if err := nDB.LeaveNetwork(nid); err != nil { - log.WithError(err).Error("leave network failed") + logger.WithError(err).Error("leave network failed") diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) return } - log.Info("leave network done") + logger.Info("leave network done") diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) return } @@ -368,18 +412,23 @@ func dbLeaveNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) { } func dbGetTable(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() + _ = r.ParseForm() diagnostic.DebugHTTPForm(r) unsafe, json := diagnostic.ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("get table") + logger := log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }) + logger.Info("get table") if len(r.Form["tname"]) < 1 || len(r.Form["nid"]) < 1 { rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id", r.URL.Path)) - log.Error("get table failed, wrong input") + logger.Error("get table failed, wrong input") diagnostic.HTTPReply(w, rsp, json) return } @@ -408,7 +457,7 @@ func dbGetTable(ctx interface{}, w http.ResponseWriter, r *http.Request) { }) i++ } - log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("get table done") + logger.WithField("response", fmt.Sprintf("%+v", rsp)).Info("get table done") diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json) return } @@ -416,17 +465,22 @@ func dbGetTable(ctx interface{}, w http.ResponseWriter, r *http.Request) { } func dbNetworkStats(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() + _ = r.ParseForm() diagnostic.DebugHTTPForm(r) _, json := diagnostic.ParseHTTPFormOptions(r) // audit logs - log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("network stats") + logger := log.G(context.TODO()).WithFields(log.Fields{ + "component": "diagnostic", + "remoteIP": r.RemoteAddr, + "method": caller.Name(0), + "url": r.URL.String(), + }) + logger.Info("network stats") if len(r.Form["nid"]) < 1 { rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=test", r.URL.Path)) - log.Error("network stats failed, wrong input") + logger.Error("network stats failed, wrong input") diagnostic.HTTPReply(w, rsp, json) return } @@ -446,7 +500,7 @@ func dbNetworkStats(ctx interface{}, w http.ResponseWriter, r *http.Request) { nDB.RUnlock() rsp := diagnostic.CommandSucceed(&diagnostic.NetworkStatsResult{Entries: entries, QueueLen: qLen}) - log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("network stats done") + logger.WithField("response", fmt.Sprintf("%+v", rsp)).Info("network stats done") diagnostic.HTTPReply(w, rsp, json) return } diff --git a/libnetwork/resolver.go b/libnetwork/resolver.go index 3c492b1558..9786ccefcf 100644 --- a/libnetwork/resolver.go +++ b/libnetwork/resolver.go @@ -522,12 +522,12 @@ func (r *Resolver) exchange(proto string, extDNS extDNSEntry, query *dns.Msg) *d } defer extConn.Close() - log := r.log().WithFields(logrus.Fields{ + logger := r.log().WithFields(log.Fields{ "dns-server": extConn.RemoteAddr().Network() + ":" + extConn.RemoteAddr().String(), "client-addr": extConn.LocalAddr().Network() + ":" + extConn.LocalAddr().String(), "question": query.Question[0].String(), }) - log.Debug("[resolver] forwarding query") + logger.Debug("[resolver] forwarding query") resp, _, err := (&dns.Client{ Timeout: extIOTimeout, @@ -549,7 +549,7 @@ func (r *Resolver) exchange(proto string, extDNS extDNSEntry, query *dns.Msg) *d if resp == nil { // Should be impossible, so make noise if it happens anyway. - log.Error("[resolver] external DNS returned empty response") + logger.Error("[resolver] external DNS returned empty response") } return resp } diff --git a/pkg/archive/archive.go b/pkg/archive/archive.go index 6a9ec9fa61..3198b60ca8 100644 --- a/pkg/archive/archive.go +++ b/pkg/archive/archive.go @@ -30,7 +30,6 @@ import ( "github.com/moby/patternmatcher" "github.com/moby/sys/sequential" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) // ImpliedDirectoryMode represents the mode (Unix permissions) applied to directories that are implied by files in a @@ -790,7 +789,7 @@ func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, o } if len(xattrErrs) > 0 { - log.G(context.TODO()).WithFields(logrus.Fields{ + log.G(context.TODO()).WithFields(log.Fields{ "errors": xattrErrs, }).Warn("ignored xattrs in archive: underlying filesystem doesn't support them") } diff --git a/plugin/executor/containerd/containerd.go b/plugin/executor/containerd/containerd.go index a9e939255d..d3611d2725 100644 --- a/plugin/executor/containerd/containerd.go +++ b/plugin/executor/containerd/containerd.go @@ -76,13 +76,12 @@ func (p c8dPlugin) deleteTaskAndContainer(ctx context.Context) { // Create creates a new container func (e *Executor) Create(id string, spec specs.Spec, stdout, stderr io.WriteCloser) error { ctx := context.Background() - log := log.G(ctx).WithField("plugin", id) ctr, err := libcontainerd.ReplaceContainer(ctx, e.client, id, &spec, e.shim, e.shimOpts) if err != nil { return errors.Wrap(err, "error creating containerd container for plugin") } - p := c8dPlugin{log: log, ctr: ctr} + p := c8dPlugin{log: log.G(ctx).WithField("plugin", id), ctr: ctr} p.tsk, err = ctr.Start(ctx, "", false, attachStreamsFunc(stdout, stderr)) if err != nil { p.deleteTaskAndContainer(ctx) diff --git a/plugin/manager.go b/plugin/manager.go index 67f2131c3e..6205495c24 100644 --- a/plugin/manager.go +++ b/plugin/manager.go @@ -311,7 +311,7 @@ func (logHook) Levels() []logrus.Level { } func (l logHook) Fire(entry *logrus.Entry) error { - entry.Data = logrus.Fields{"plugin": l.id} + entry.Data = log.Fields{"plugin": l.id} return nil } diff --git a/registry/config.go b/registry/config.go index 326b2ec3c6..696f3ecf9a 100644 --- a/registry/config.go +++ b/registry/config.go @@ -1,15 +1,16 @@ package registry // import "github.com/docker/docker/registry" import ( + "context" "net" "net/url" "regexp" "strconv" "strings" + "github.com/containerd/containerd/log" "github.com/docker/distribution/reference" "github.com/docker/docker/api/types/registry" - "github.com/sirupsen/logrus" ) // ServiceOptions holds command line options. @@ -197,10 +198,10 @@ skip: return err } if strings.HasPrefix(strings.ToLower(r), "http://") { - logrus.Warnf("insecure registry %s should not contain 'http://' and 'http://' has been removed from the insecure registry config", r) + log.G(context.TODO()).Warnf("insecure registry %s should not contain 'http://' and 'http://' has been removed from the insecure registry config", r) r = r[7:] } else if strings.HasPrefix(strings.ToLower(r), "https://") { - logrus.Warnf("insecure registry %s should not contain 'https://' and 'https://' has been removed from the insecure registry config", r) + log.G(context.TODO()).Warnf("insecure registry %s should not contain 'https://' and 'https://' has been removed from the insecure registry config", r) r = r[8:] } else if hasScheme(r) { return invalidParamf("insecure registry %s should not contain '://'", r) diff --git a/volume/local/local.go b/volume/local/local.go index d7da589a2e..ebbb097aa5 100644 --- a/volume/local/local.go +++ b/volume/local/local.go @@ -19,7 +19,6 @@ import ( "github.com/docker/docker/quota" "github.com/docker/docker/volume" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) const ( @@ -390,7 +389,7 @@ func (v *localVolume) LiveRestoreVolume(ctx context.Context, _ string) error { } v.active.count++ v.active.mounted = true - log.G(ctx).WithFields(logrus.Fields{ + log.G(ctx).WithFields(log.Fields{ "volume": v.name, "active mounts": v.active, }).Debugf("Live restored volume") diff --git a/volume/mounts/mounts.go b/volume/mounts/mounts.go index 188d693f88..2144d97f3a 100644 --- a/volume/mounts/mounts.go +++ b/volume/mounts/mounts.go @@ -14,7 +14,6 @@ import ( "github.com/docker/docker/volume" "github.com/opencontainers/selinux/go-selinux/label" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) // MountPoint is the intersection point between a volume and a container. It @@ -169,7 +168,7 @@ func (m *MountPoint) Setup(mountLabel string, rootIDs idtools.Identity, checkFun func (m *MountPoint) LiveRestore(ctx context.Context) error { if m.Volume == nil { - logrus.Debug("No volume to restore") + log.G(ctx).Debug("No volume to restore") return nil }