Add stderr to log messages

This commit is contained in:
Evan Fiordeliso 2024-09-18 20:46:18 -04:00
parent f6d1ecd757
commit 9dff066a9c
4 changed files with 32 additions and 17 deletions

View File

@ -32,12 +32,16 @@ func Exec(binary, url string, options ...Option) error {
cmd.Stdout = opts.stdout cmd.Stdout = opts.stdout
} }
var stderr = new(bytes.Buffer)
if opts.stderr != nil { if opts.stderr != nil {
cmd.Stderr = opts.stderr cmd.Stderr = stderr
} }
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
return err return &Error{
stderr: stderr.String(),
child: err,
}
} }
buf, bufOk := opts.stdout.(*bytes.Buffer) buf, bufOk := opts.stdout.(*bytes.Buffer)

View File

@ -7,9 +7,7 @@ import (
"io" "io"
"strings" "strings"
"go.fifitido.net/ytdl-web/pkg/utils"
"go.fifitido.net/ytdl-web/pkg/ytdl/metadata" "go.fifitido.net/ytdl-web/pkg/ytdl/metadata"
"golang.org/x/exp/slog"
) )
type Options struct { 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 { func WithPlaylistIndex(index int) Option {
return func(opts *Options) error { return func(opts *Options) error {
opts.args = append(opts.args, "--playlist-items", fmt.Sprint(index+1)) opts.args = append(opts.args, "--playlist-items", fmt.Sprint(index+1))

14
pkg/ytdl/error.go Normal file
View File

@ -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
}

View File

@ -2,6 +2,7 @@ package ytdl
import ( import (
"bytes" "bytes"
"errors"
"io" "io"
"os/exec" "os/exec"
"strings" "strings"
@ -63,10 +64,6 @@ func (y *ytdlImpl) baseOptions(url string) []Option {
} }
} }
if y.cfg.IsDevelopment() {
options = append(options, WithDebug())
}
return options 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 { 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 return nil, err
} }