From 9dff066a9c8a9924509ce40c80a89764ba8452ea Mon Sep 17 00:00:00 2001 From: Evan Fiordeliso Date: Wed, 18 Sep 2024 20:46:18 -0400 Subject: [PATCH] Add stderr to log messages --- pkg/ytdl/cmdbuilder.go | 8 ++++++-- pkg/ytdl/cmdopts.go | 10 ---------- pkg/ytdl/error.go | 14 ++++++++++++++ pkg/ytdl/ytdl.go | 17 ++++++++++++----- 4 files changed, 32 insertions(+), 17 deletions(-) create mode 100644 pkg/ytdl/error.go diff --git a/pkg/ytdl/cmdbuilder.go b/pkg/ytdl/cmdbuilder.go index 4fddc2e..c3eea43 100644 --- a/pkg/ytdl/cmdbuilder.go +++ b/pkg/ytdl/cmdbuilder.go @@ -32,12 +32,16 @@ func Exec(binary, url string, options ...Option) error { cmd.Stdout = opts.stdout } + var stderr = new(bytes.Buffer) if opts.stderr != nil { - cmd.Stderr = opts.stderr + cmd.Stderr = stderr } if err := cmd.Run(); err != nil { - return err + return &Error{ + stderr: stderr.String(), + child: err, + } } buf, bufOk := opts.stdout.(*bytes.Buffer) diff --git a/pkg/ytdl/cmdopts.go b/pkg/ytdl/cmdopts.go index 436cbda..ec15215 100644 --- a/pkg/ytdl/cmdopts.go +++ b/pkg/ytdl/cmdopts.go @@ -7,9 +7,7 @@ import ( "io" "strings" - "go.fifitido.net/ytdl-web/pkg/utils" "go.fifitido.net/ytdl-web/pkg/ytdl/metadata" - "golang.org/x/exp/slog" ) type Options struct { @@ -93,14 +91,6 @@ func WithStreamOutput(output io.Writer) Option { } } -func WithDebug() Option { - return func(opts *Options) error { - opts.stdout = utils.LoggerWriter(slog.With("module", "ytdl"), slog.LevelDebug) - opts.stderr = utils.LoggerWriter(slog.With("module", "ytdl"), slog.LevelDebug) - return nil - } -} - func WithPlaylistIndex(index int) Option { return func(opts *Options) error { opts.args = append(opts.args, "--playlist-items", fmt.Sprint(index+1)) diff --git a/pkg/ytdl/error.go b/pkg/ytdl/error.go new file mode 100644 index 0000000..74ba066 --- /dev/null +++ b/pkg/ytdl/error.go @@ -0,0 +1,14 @@ +package ytdl + +type Error struct { + stderr string + child error +} + +func (e *Error) Error() string { + return e.child.Error() +} + +func (e *Error) Stderr() string { + return e.stderr +} diff --git a/pkg/ytdl/ytdl.go b/pkg/ytdl/ytdl.go index 0d3653d..63edd63 100644 --- a/pkg/ytdl/ytdl.go +++ b/pkg/ytdl/ytdl.go @@ -2,6 +2,7 @@ package ytdl import ( "bytes" + "errors" "io" "os/exec" "strings" @@ -63,10 +64,6 @@ func (y *ytdlImpl) baseOptions(url string) []Option { } } - if y.cfg.IsDevelopment() { - options = append(options, WithDebug()) - } - return options } @@ -88,7 +85,17 @@ func (y *ytdlImpl) GetMetadata(url string) (*metadata.Metadata, error) { ) if err := Exec(y.cfg.BinaryPath, url, options...); err != nil { - y.logger.Error("failed to get metadata", slog.String("url", url), slog.String("error", err.Error())) + attrs := []any{ + slog.String("url", url), + slog.String("error", err.Error()), + } + + var ytdlErr *Error + if ok := errors.As(err, &ytdlErr); ok { + attrs = append(attrs, slog.String("stderr", ytdlErr.Stderr())) + } + + y.logger.Error("failed to get metadata", attrs...) return nil, err }