Skip to content

Commit 8eabf5f

Browse files
committed
Use log/slog package
Minimum Go version required: 1.21
1 parent 31bf9e2 commit 8eabf5f

File tree

15 files changed

+88
-68
lines changed

15 files changed

+88
-68
lines changed

.github/workflows/go.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ jobs:
99
strategy:
1010
matrix:
1111
platform: [ubuntu-22.04]
12-
go-version: [1.21.x, 1.20.x]
12+
go-version: [1.21.x, 1.x]
1313
runs-on: ${{ matrix.platform }}
1414
name: Linters (Static Analysis) for Go
1515
steps:
@@ -27,7 +27,7 @@ jobs:
2727
strategy:
2828
matrix:
2929
platform: [ubuntu-22.04]
30-
go-version: [1.21.x, 1.20.x]
30+
go-version: [1.21.x, 1.x]
3131
runs-on: ${{ matrix.platform }}
3232
name: integration tests
3333
env:

.github/workflows/schedule.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ jobs:
99
strategy:
1010
matrix:
1111
platform: [ubuntu-22.04]
12-
go-version: [1.20.x]
12+
go-version: [1.21.x]
1313
runs-on: ${{ matrix.platform }}
1414
name: integration tests
1515
env:

Makefile

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
FILES_TO_FMT ?= $(shell find . -path ./vendor -prune -o -name '*.go' -print)
2+
LOGLEVEL ?= debug
23

34
## help: Show makefile commands
45
.PHONY: help
@@ -38,14 +39,14 @@ format:
3839
## test-unit: Run all Youtube Go unit tests
3940
.PHONY: test-unit
4041
test-unit:
41-
go test -v -cover ./...
42+
LOGLEVEL=${LOGLEVEL} go test -v -cover ./...
4243

4344
## test-integration: Run all Youtube Go integration tests
4445
.PHONY: test-integration
4546
test-integration:
4647
mkdir -p output
4748
rm -f output/*
48-
ARTIFACTS=output go test -race -covermode=atomic -coverprofile=coverage.out -tags=integration ./...
49+
LOGLEVEL=${LOGLEVEL} ARTIFACTS=output go test -v -race -covermode=atomic -coverprofile=coverage.out -tags=integration ./...
4950

5051
.PHONY: coverage.out
5152
coverage.out:

artifacts.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package youtube
22

33
import (
4-
"log"
4+
"log/slog"
55
"os"
66
"path/filepath"
77
)
@@ -13,15 +13,17 @@ func writeArtifact(name string, content []byte) {
1313
// Ensure folder exists
1414
err := os.MkdirAll(artifactsFolder, os.ModePerm)
1515
if err != nil {
16-
log.Printf("unable to create artifacts folder %s: %s", artifactsFolder, err)
16+
slog.Error("unable to create artifacts folder", "path", artifactsFolder, "error", err)
1717
return
1818
}
1919

2020
path := filepath.Join(artifactsFolder, name)
2121
err = os.WriteFile(path, content, 0600)
22+
23+
log := slog.With("path", path)
2224
if err != nil {
23-
log.Printf("unable to write artifact %s: %v", path, err)
25+
log.Error("unable to write artifact", "error", err)
2426
} else {
25-
log.Println("artifact created:", path)
27+
log.Debug("artifact created")
2628
}
2729
}

client.go

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,13 @@ import (
77
"errors"
88
"fmt"
99
"io"
10-
"log"
1110
"math/rand"
1211
"net/http"
1312
"net/url"
1413
"strconv"
1514
"sync/atomic"
15+
16+
"log/slog"
1617
)
1718

1819
const (
@@ -32,9 +33,6 @@ var DefaultClient = AndroidClient
3233

3334
// Client offers methods to download video metadata and video streams.
3435
type Client struct {
35-
// Debug enables debugging output through log package
36-
Debug bool
37-
3836
// HTTPClient can be used to set a custom HTTP client.
3937
// If not set, http.DefaultClient will be used
4038
HTTPClient *http.Client
@@ -484,10 +482,6 @@ func (c *Client) httpDo(req *http.Request) (*http.Response, error) {
484482
client = http.DefaultClient
485483
}
486484

487-
if c.Debug {
488-
log.Println(req.Method, req.URL)
489-
}
490-
491485
req.Header.Set("User-Agent", c.client.userAgent)
492486
req.Header.Set("Origin", "https://youtube.com")
493487
req.Header.Set("Sec-Fetch-Mode", "navigate")
@@ -505,8 +499,12 @@ func (c *Client) httpDo(req *http.Request) (*http.Response, error) {
505499

506500
res, err := client.Do(req)
507501

508-
if c.Debug && res != nil {
509-
log.Println(res.Status)
502+
log := slog.With("method", req.Method, "url", req.URL)
503+
504+
if err != nil {
505+
log.Debug("HTTP request failed", "error", err)
506+
} else {
507+
log.Debug("HTTP request succeeded", "status", res.Status)
510508
}
511509

512510
return res, err

client_test.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,15 @@ import (
1010
"golang.org/x/net/context"
1111
)
1212

13-
var testClient = Client{Debug: true}
14-
var testWebClient = Client{Debug: true, client: &WebClient}
15-
1613
const (
1714
dwlURL string = "https://www.youtube.com/watch?v=rFejpH_tAHM"
1815
streamURL string = "https://www.youtube.com/watch?v=a9LDPn-MO4I"
1916
errURL string = "https://www.youtube.com/watch?v=I8oGsuQ"
2017
)
2118

19+
var testClient = Client{}
20+
var testWebClient = Client{client: &WebClient}
21+
2222
func TestParseVideo(t *testing.T) {
2323
video, err := testClient.GetVideo(dwlURL)
2424
assert.NoError(t, err)
@@ -162,7 +162,6 @@ func TestGetStream(t *testing.T) {
162162

163163
// Create testclient to enforce re-using of routines
164164
testClient := Client{
165-
Debug: true,
166165
MaxRoutines: 10,
167166
ChunkSize: int64(expectedSize) / 11,
168167
}

cmd/youtubedr/downloader.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"crypto/tls"
55
"errors"
66
"fmt"
7-
"log"
87
"net"
98
"net/http"
109
"net/url"
@@ -54,8 +53,10 @@ func getDownloader() *ytdl.Downloader {
5453
}).DialContext,
5554
}
5655

56+
youtube.SetLogLevel(logLevel)
57+
5758
if insecureSkipVerify {
58-
log.Println("Skip server certificate verification")
59+
youtube.Logger.Info("Skip server certificate verification")
5960
httpTransport.TLSClientConfig = &tls.Config{
6061
InsecureSkipVerify: true,
6162
}
@@ -64,7 +65,6 @@ func getDownloader() *ytdl.Downloader {
6465
downloader = &ytdl.Downloader{
6566
OutputDir: outputDir,
6667
}
67-
downloader.Client.Debug = verbose
6868
downloader.HTTPClient = &http.Client{Transport: httpTransport}
6969

7070
return downloader

cmd/youtubedr/root.go

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@ package main
22

33
import (
44
"fmt"
5-
"io"
6-
"log"
75
"os"
86

97
homedir "github.com/mitchellh/go-homedir"
@@ -12,8 +10,8 @@ import (
1210
)
1311

1412
var (
15-
cfgFile string
16-
verbose bool
13+
cfgFile string
14+
logLevel string
1715
)
1816

1917
// rootCmd represents the base command when called without any subcommands
@@ -31,18 +29,13 @@ Use the HTTP_PROXY environment variable to set a HTTP or SOCSK5 proxy. The proxy
3129

3230
func init() {
3331
cobra.OnInitialize(initConfig)
34-
cobra.OnInitialize(func() {
35-
if !verbose {
36-
log.SetOutput(io.Discard)
37-
}
38-
})
3932

4033
// Here you will define your flags and configuration settings.
4134
// Cobra supports persistent flags, which, if defined here,
4235
// will be global for your application.
4336

4437
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.youtubedr.yaml)")
45-
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Enable verbose output")
38+
rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "info", "Set log level (error/warn/info/debug)")
4639
rootCmd.PersistentFlags().BoolVar(&insecureSkipVerify, "insecure", false, "Skip TLS server certificate verification")
4740
}
4841

decipher.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"context"
66
"errors"
77
"fmt"
8-
"log"
98
"net/url"
109
"regexp"
1110
"strconv"
@@ -76,17 +75,18 @@ func (c *Client) unThrottle(ctx context.Context, videoID string, urlString strin
7675
func (c *Client) decryptNParam(config playerConfig, query url.Values) (url.Values, error) {
7776
// decrypt n-parameter
7877
nSig := query.Get("v")
78+
log := Logger.With("n", nSig)
79+
7980
if nSig != "" {
8081
nDecoded, err := config.decodeNsig(nSig)
8182
if err != nil {
8283
return nil, fmt.Errorf("unable to decode nSig: %w", err)
8384
}
8485
query.Set("v", nDecoded)
86+
log = log.With("decoded", nDecoded)
8587
}
8688

87-
if c.Debug {
88-
log.Printf("[nParam] n: %s; nDecoded: %s\nQuery: %v\n", nSig, query.Get("v"), query)
89-
}
89+
log.Debug("nParam")
9090

9191
return query, nil
9292
}

downloader/downloader.go

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"context"
55
"fmt"
66
"io"
7-
"log"
87
"os"
98
"os/exec"
109
"path/filepath"
@@ -38,7 +37,12 @@ func (dl *Downloader) getOutputFile(v *youtube.Video, format *youtube.Format, ou
3837

3938
// Download : Starting download video by arguments.
4039
func (dl *Downloader) Download(ctx context.Context, v *youtube.Video, format *youtube.Format, outputFile string) error {
41-
dl.logf("Video '%s' - Quality '%s' - Codec '%s'", v.Title, format.QualityLabel, format.MimeType)
40+
youtube.Logger.Info(
41+
"Downloading video",
42+
"id", v.ID,
43+
"quality", format.Quality,
44+
"mimeType", format.MimeType,
45+
)
4246
destFile, err := dl.getOutputFile(v, format, outputFile)
4347
if err != nil {
4448
return err
@@ -51,7 +55,6 @@ func (dl *Downloader) Download(ctx context.Context, v *youtube.Video, format *yo
5155
}
5256
defer out.Close()
5357

54-
dl.logf("Download to file=%s", destFile)
5558
return dl.videoDLWorker(ctx, out, v, format)
5659
}
5760

@@ -62,7 +65,15 @@ func (dl *Downloader) DownloadComposite(ctx context.Context, outputFile string,
6265
return err1
6366
}
6467

65-
dl.logf("Video '%s' - Quality '%s' - Video Codec '%s' - Audio Codec '%s'", v.Title, videoFormat.QualityLabel, videoFormat.MimeType, audioFormat.MimeType)
68+
log := youtube.Logger.With("id", v.ID)
69+
70+
log.Info(
71+
"Downloading composite video",
72+
"videoQuality", videoFormat.QualityLabel,
73+
"videoMimeType", videoFormat.MimeType,
74+
"audioMimeType", audioFormat.MimeType,
75+
)
76+
6677
destFile, err := dl.getOutputFile(v, videoFormat, outputFile)
6778
if err != nil {
6879
return err
@@ -83,13 +94,13 @@ func (dl *Downloader) DownloadComposite(ctx context.Context, outputFile string,
8394
}
8495
defer os.Remove(audioFile.Name())
8596

86-
dl.logf("Downloading video file...")
97+
log.Debug("Downloading video file...")
8798
err = dl.videoDLWorker(ctx, videoFile, v, videoFormat)
8899
if err != nil {
89100
return err
90101
}
91102

92-
dl.logf("Downloading audio file...")
103+
log.Debug("Downloading audio file...")
93104
err = dl.videoDLWorker(ctx, audioFile, v, audioFormat)
94105
if err != nil {
95106
return err
@@ -106,7 +117,7 @@ func (dl *Downloader) DownloadComposite(ctx context.Context, outputFile string,
106117
)
107118
ffmpegVersionCmd.Stderr = os.Stderr
108119
ffmpegVersionCmd.Stdout = os.Stdout
109-
dl.logf("merging video and audio to %s", destFile)
120+
log.Info("merging video and audio", "output", destFile)
110121

111122
return ffmpegVersionCmd.Run()
112123
}
@@ -184,9 +195,3 @@ func (dl *Downloader) videoDLWorker(ctx context.Context, out *os.File, video *yo
184195
progress.Wait()
185196
return nil
186197
}
187-
188-
func (dl *Downloader) logf(format string, v ...interface{}) {
189-
if dl.Debug {
190-
log.Printf(format, v...)
191-
}
192-
}

0 commit comments

Comments
 (0)