From 31876a3271288f31555051334c95b41a123f0f3c Mon Sep 17 00:00:00 2001 From: buty4649 Date: Wed, 20 Mar 2024 17:01:22 +0900 Subject: [PATCH] Add logger to iproute2 and update slog usage --- cmd/root.go | 6 ++++-- iproute2/iproute2.go | 10 +++++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 17af63f..961daa0 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -63,11 +63,12 @@ var rootCmd = &cobra.Command{ if flags.Quiet { logLevel = slog.LevelError } - slog.SetDefault(slog.New(slogor.NewHandler(os.Stdout, slogor.Options{ + logger := slog.New(slogor.NewHandler(os.Stdout, slogor.Options{ TimeFormat: "", Level: logLevel, ShowSource: false, - }))) + })) + slog.SetDefault(logger) cfg, err = config.LoadConfig(flags.ConfigPath) if err != nil { @@ -75,6 +76,7 @@ var rootCmd = &cobra.Command{ } ip = iproute2.New(flags.IpCmdPath) + iproute2.SetLogger(logger) return nil }, } diff --git a/iproute2/iproute2.go b/iproute2/iproute2.go index 7dcd029..6e7aa9a 100644 --- a/iproute2/iproute2.go +++ b/iproute2/iproute2.go @@ -43,6 +43,8 @@ type Error struct { Message string } +var logger *slog.Logger + func New(path string) *Iproute2 { return &Iproute2{ path: path, @@ -51,6 +53,10 @@ func New(path string) *Iproute2 { } } +func SetLogger(l *slog.Logger) { + logger = l +} + func (i *Iproute2) AddLink(name string, linkType string, options ...string) error { args := []string{"link", "add", "name", name, "type", linkType} args = append(args, options...) @@ -189,7 +195,9 @@ func (i *Iproute2) executeWithStdout(args ...string) (string, error) { } cmdArgs = append(cmdArgs, args...) - slog.Debug(fmt.Sprintf("exec: %s %s", i.path, strings.Join(cmdArgs, " "))) + if logger != nil { + logger.Debug("exec command", "path", i.path, "args", strings.Join(cmdArgs, " ")) + } cmd := exec.Command(i.path, cmdArgs...) var stdoutBuf, stderrBuf bytes.Buffer