Skip to content

Commit bf0ffa0

Browse files
committed
Merge branch 'feat/slog' into dev
2 parents dba97ec + b432f63 commit bf0ffa0

File tree

15 files changed

+144
-120
lines changed

15 files changed

+144
-120
lines changed

src/client/client.go

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ package client
22

33
import (
44
"fmt"
5-
"log"
5+
"log/slog"
66
"time"
77

88
"explo/src/config"
@@ -54,7 +54,7 @@ func NewClient(cfg *config.Config, httpClient *util.HttpClient) (*Client, error)
5454
c.API = NewSubsonic(cfg.ClientCfg, httpClient)
5555

5656
default:
57-
log.Fatalf("unknown system: %s. Use a supported system (emby, jellyfin, mpd, plex, or subsonic).", c.System)
57+
return nil, fmt.Errorf("unknown system: %s. Use a supported system (emby, jellyfin, mpd, plex, or subsonic)", c.System)
5858
}
5959

6060
if err := c.systemSetup(); err != nil { // Run setup automatically
@@ -122,25 +122,26 @@ func (c *Client) systemSetup() error {
122122
}
123123
}
124124

125-
func (c *Client) CheckTracks(tracks []*models.Track) {
125+
func (c *Client) CheckTracks(tracks []*models.Track) error {
126126
if err := c.API.SearchSongs(tracks); err != nil {
127-
log.Printf("warning: SearchSongs failed: %v", err)
127+
return fmt.Errorf("SearchSongs failed: %s", err.Error())
128128
}
129+
return nil
129130
}
130131

131132
func (c *Client) CreatePlaylist(tracks []*models.Track) error {
132133
if c.System == "" {
133-
log.Fatal("could not get music system")
134+
return fmt.Errorf("could not get music system")
134135
}
135136

136137
if err := c.API.RefreshLibrary(); err != nil {
137138
return fmt.Errorf("[%s] failed to schedule a library scan: %s", c.System, err.Error())
138139
}
139140

140-
log.Printf("[%s] Refreshing library...", c.System)
141+
slog.Info("Refreshing library...", "system", c.System)
141142
time.Sleep(time.Duration(c.Cfg.Sleep) * time.Minute)
142143
if err := c.API.SearchSongs(tracks); err != nil { // search newly added songs
143-
log.Printf("warning: SearchSongs failed: %v", err)
144+
slog.Warn("SearchSongs failed", "context", err)
144145
}
145146
if err := c.API.CreatePlaylist(tracks); err != nil {
146147
return fmt.Errorf("[%s] failed to create playlist: %s", c.System, err.Error())
@@ -154,7 +155,7 @@ func (c *Client) CreatePlaylist(tracks []*models.Track) error {
154155

155156
func (c *Client) DeletePlaylist() error {
156157
if err := c.API.SearchPlaylist(); err != nil {
157-
return fmt.Errorf("warning: SearchSongs failed: %v", err)
158+
return fmt.Errorf("SearchPlaylist failed: %v", err)
158159
}
159160
if err := c.API.DeletePlaylist(); err != nil {
160161
return fmt.Errorf("[%s] failed to delete playlist: %s", c.System, err.Error())

src/client/emby.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,12 @@ package client
33
import (
44
"bytes"
55
"fmt"
6-
"log"
6+
"log/slog"
77
"strings"
88
"time"
99
"net/url"
1010

1111
"explo/src/config"
12-
"explo/src/debug"
1312
"explo/src/models"
1413
"explo/src/util"
1514
)
@@ -107,7 +106,7 @@ func (c *Emby) AddLibrary() error {
107106
}`, c.Cfg.LibraryName, c.Cfg.DownloadDir)
108107

109108
if _, err := c.HttpClient.MakeRequest("POST", c.Cfg.URL+reqParam, bytes.NewReader(payload), c.Cfg.Creds.Headers); err != nil {
110-
log.Fatalf("failed to add library to Emby using the download path, please define a library name using LIBRARY_NAME in .env: %s", err.Error())
109+
return fmt.Errorf("failed to add library to Emby using the download path, please define a library name using LIBRARY_NAME in .env: %s", err.Error())
111110
}
112111
return nil
113112
}
@@ -152,7 +151,7 @@ func (c *Emby) SearchSongs(tracks []*models.Track) error {
152151
}
153152

154153
if !track.Present {
155-
debug.Debug(fmt.Sprintf("[emby] failed to find '%s' by '%s' in album '%s'", track.Title, track.Artist, track.Album))
154+
slog.Debug(fmt.Sprintf("[emby] failed to find '%s' by '%s' in album '%s'", track.Title, track.Artist, track.Album))
156155
}
157156
}
158157
return nil

src/client/jellyfin.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ import (
66
"fmt"
77
"net/url"
88
"strings"
9+
"log/slog"
910

1011
"explo/src/config"
11-
"explo/src/debug"
1212
"explo/src/models"
1313
"explo/src/util"
1414
)
@@ -161,7 +161,7 @@ func (c *Jellyfin) SearchSongs(tracks []*models.Track) error {
161161
}
162162

163163
if !track.Present {
164-
debug.Debug(fmt.Sprintf("[jellyfin] failed to find '%s' by '%s' in album '%s'", track.Title, track.Artist, track.Album))
164+
slog.Debug(fmt.Sprintf("[jellyfin] failed to find '%s' by '%s' in album '%s'", track.Title, track.Artist, track.Album))
165165
}
166166
}
167167
return nil

src/client/mpd.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ import (
55
"fmt"
66
"os"
77
"path/filepath"
8+
"log/slog"
89

910
"explo/src/config"
10-
"explo/src/debug"
1111
"explo/src/models"
1212
)
1313

@@ -69,7 +69,7 @@ func (c *MPD) CreatePlaylist(tracks []*models.Track) error {
6969
if track.Present {
7070
_, err := f.Write([]byte(track.File+"\n"))
7171
if err != nil {
72-
debug.Debug(fmt.Sprintf("failed to write song to file: %s", err.Error()))
72+
slog.Warn(fmt.Sprintf("failed to write song to file: %s", err.Error()))
7373
}
7474
}
7575
}

src/client/plex.go

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,11 @@ import (
44
"bytes"
55
"encoding/json"
66
"fmt"
7-
"log"
7+
"log/slog"
88
"net/url"
99
"strings"
1010

1111
"explo/src/config"
12-
"explo/src/debug"
1312
"explo/src/models"
1413
"explo/src/util"
1514
)
@@ -193,8 +192,8 @@ func (c *Plex) GetLibrary() error {
193192
}
194193
}
195194
if err = c.AddLibrary(); err != nil {
196-
debug.Debug(err.Error())
197-
log.Fatalf("library named %s not found and cannot be added, please create it manually and ensure 'Prefer local metadata' is checked", c.Cfg.LibraryName)
195+
slog.Debug(err.Error())
196+
return fmt.Errorf("library named %s not found and cannot be added, please create it manually and ensure 'Prefer local metadata' is checked", c.Cfg.LibraryName)
198197
}
199198
return fmt.Errorf("library '%s' not found", c.Cfg.LibraryName)
200199
}
@@ -230,18 +229,18 @@ func (c *Plex) SearchSongs(tracks []*models.Track) error {
230229

231230
body, err := c.HttpClient.MakeRequest("GET", c.Cfg.URL+params, nil, c.Cfg.Creds.Headers)
232231
if err != nil {
233-
log.Printf("search request failed for '%s': %s", track.Title, err.Error())
232+
slog.Warn("search request failed for '%s': %s", track.Title, err.Error())
234233
continue
235234
}
236235

237236
var searchResults PlexSearch
238237
if err = util.ParseResp(body, &searchResults); err != nil {
239-
log.Printf("failed to parse response for '%s': %s", track.Title, err.Error())
238+
slog.Warn("failed to parse response for '%s': %s", track.Title, err.Error())
240239
continue
241240
}
242241
key, err := getPlexSong(track, searchResults)
243242
if err != nil {
244-
debug.Debug(err.Error())
243+
slog.Debug(err.Error())
245244
continue
246245
}
247246
if key != "" {
@@ -345,7 +344,7 @@ func getPlexSong(track *models.Track, searchResults PlexSearch) (string, error)
345344
artistMatch := strings.Contains(strings.ToLower(md.OriginalTitle), loweredArtist) || strings.Contains(strings.ToLower(md.GrandparentTitle), loweredArtist)
346345

347346
if titleMatch && (albumMatch || artistMatch) {
348-
debug.Debug(fmt.Sprintf("matched track via metadata: %s by %s Plex Key: %s", track.Title, track.Artist, md.Key))
347+
slog.Debug(fmt.Sprintf("matched track via metadata: %s by %s", track.Title, track.Artist))
349348
return md.Key, nil
350349
}
351350

@@ -358,12 +357,12 @@ func getPlexSong(track *models.Track, searchResults PlexSearch) (string, error)
358357
durationMatch := util.Abs(media.Duration - track.Duration) < 10000 // duration within 10s
359358

360359
if durationMatch && pathMatch {
361-
debug.Debug(fmt.Sprintf("matched track via path: %s by %s Plex Key: %s", track.Title, track.Artist, md.Key))
360+
slog.Debug(fmt.Sprintf("matched track via path: %s by %s", track.Title, track.Artist))
362361
return md.Key, nil
363362
}
364363
}
365364

366-
debug.Debug(fmt.Sprintf("full search result: %v", searchResults.MediaContainer.SearchResult))
365+
slog.Debug(fmt.Sprintf("full search result: %v", searchResults.MediaContainer.SearchResult))
367366
return "", fmt.Errorf("failed to find '%s' by '%s' in '%s'", track.Title, track.Artist, track.Album)
368367
}
369368

@@ -373,7 +372,7 @@ func (c *Plex) addtoPlaylist(tracks []*models.Track) {
373372
params := fmt.Sprintf("/playlists/%s/items?uri=server://%s/com.plexapp.plugins.library%s", c.Cfg.PlaylistID, c.machineID, track.ID)
374373

375374
if _, err := c.HttpClient.MakeRequest("PUT", c.Cfg.URL+params, nil, c.Cfg.Creds.Headers); err != nil {
376-
log.Printf("failed to add %s to playlist: %s", track.Title, err.Error())
375+
slog.Warn("failed to add %s to playlist: %s", track.Title, err.Error())
377376
}
378377
}
379378
}

src/client/subsonic.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@ import (
44
"fmt"
55
"strings"
66
"time"
7+
"log/slog"
78

89
"crypto/md5"
910
"crypto/rand"
1011
"encoding/base64"
1112
"net/url"
1213

1314
"explo/src/config"
14-
"explo/src/debug"
1515
"explo/src/models"
1616
"explo/src/util"
1717
)
@@ -121,7 +121,7 @@ func (c *Subsonic) SearchSongs(tracks []*models.Track) error {
121121

122122
songs := resp.SubsonicResponse.SearchResult3.Song
123123
if len(songs) == 0 {
124-
debug.Debug(fmt.Sprintf("[subsonic] no results found for %s", searchQuery))
124+
slog.Debug(fmt.Sprintf("[subsonic] no results found for %s", searchQuery))
125125
continue
126126
}
127127

@@ -151,7 +151,7 @@ func (c *Subsonic) SearchSongs(tracks []*models.Track) error {
151151
}
152152

153153
if !track.Present {
154-
debug.Debug(fmt.Sprintf("[subsonic] multiple results for %s but none matched criteria", searchQuery))
154+
slog.Debug(fmt.Sprintf("[subsonic] multiple results for %s but none matched criteria", searchQuery))
155155
}
156156
}
157157
return nil

src/config/config.go

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ package config
33
import (
44
"errors"
55
"fmt"
6-
"log"
76
"os"
87
"strings"
98
"time"
9+
"log/slog"
1010

1111
"github.com/ilyakaznacheev/cleanenv"
1212
"golang.org/x/text/cases"
@@ -21,6 +21,7 @@ type Config struct {
2121
Persist bool `env:"PERSIST" env-default:"true"`
2222
System string `env:"EXPLO_SYSTEM"`
2323
Debug bool `env:"DEBUG" env-default:"false"`
24+
LogLevel string `env:"LOG_LEVEL" env-default:"WARN"`
2425
}
2526

2627
type Flags struct {
@@ -128,10 +129,12 @@ func (cfg *Config) ReadEnv() {
128129
// If the error is because the file doesn't exist, fallback to env vars
129130
if errors.Is(err, os.ErrNotExist) {
130131
if err := cleanenv.ReadEnv(&cfg); err != nil {
131-
log.Fatalf("failed to load config from env vars: %s", err)
132+
slog.Error("failed to load config from env vars", "context", err.Error())
133+
os.Exit(1)
132134
}
133135
} else {
134-
log.Fatalf("failed to load config file %s: %s", cfg.Flags.CfgPath, err)
136+
slog.Error("failed to load config file", "path", cfg.Flags.CfgPath, "context", err.Error())
137+
os.Exit(1)
135138
}
136139
}
137140

@@ -153,24 +156,13 @@ func fixDir(dir string) string {
153156
return dir
154157
}
155158

156-
/* func (cfg *Config) HandleDeprecation() { // no deprecations at the moment (keeping this for reference)
157-
switch cfg.System {
158-
case "subsonic":
159-
if cfg.Subsonic.User != "" && cfg.Creds.User == "" {
160-
log.Println("Warning: 'SUBSONIC_USER' is deprecated. Please use 'SYSTEM_USERNAME'.")
161-
cfg.Creds.User = cfg.Subsonic.User
162-
}
163-
if cfg.Subsonic.Password != "" && cfg.Creds.Password == "" {
164-
log.Println("Warning: 'SUBSONIC_PASSWORD' is deprecated. Please use 'SYSTEM_PASSWORD'.")
165-
cfg.Creds.Password = cfg.Subsonic.Password
166-
}
167-
if cfg.Subsonic.URL != "" && cfg.URL == "" {
168-
log.Println("Warning: 'SUBSONIC_URL' is deprecated. Please use 'SYSTEM_URL'.")
169-
cfg.URL = cfg.Subsonic.URL
170-
}
159+
func (cfg *Config) HandleDeprecation() { //
160+
if cfg.Debug {
161+
slog.Warn("'DEBUG' variable is deprecated, please use LOG_LEVEL=DEBUG instead")
162+
cfg.LogLevel = "DEBUG"
171163
}
172164
}
173-
*/
165+
174166
func (cfg *Config) GetPlaylistName() { // Generate playlist name and description
175167

176168
toTitle := cases.Title(language.Und)

src/debug/debug.go

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,41 @@
11
package debug
22

33
import (
4-
"log"
4+
//"log"
55
"runtime"
6+
"log/slog"
67
)
78

8-
var debugMode bool
99

10-
func Init(mode bool) {
11-
debugMode = mode
10+
func Init(level string) {
11+
slog.SetLogLoggerLevel(getLogLevel(level))
1212
}
1313

14-
func Debug(ctx string) {
15-
if debugMode {
14+
func RuntimeAttr(ctx string) slog.Attr {
1615
_, file, line, ok := runtime.Caller(1)
1716
if ok {
18-
log.Printf("DEBUG: %s:%d %s", file, line, ctx)
17+
return slog.Group("runtime",
18+
slog.String("file", file),
19+
slog.Int("line", line),
20+
slog.String("ctx", ctx),
21+
)
1922
} else {
20-
log.Printf("DEBUG: %s", ctx)
23+
return slog.String("msg", "failed getting runtime")
2124
}
25+
}
26+
27+
func getLogLevel(level string) slog.Level {
28+
29+
switch level {
30+
case "DEBUG":
31+
return slog.LevelDebug
32+
case "INFO":
33+
return slog.LevelInfo
34+
case "WARN":
35+
return slog.LevelWarn
36+
case "ERROR":
37+
return slog.LevelError
38+
default:
39+
return slog.LevelWarn
2240
}
2341
}

src/discovery/listenbrainz.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ import (
44
"fmt"
55
"strings"
66
"time"
7+
"log/slog"
78

89
cfg "explo/src/config"
9-
"explo/src/debug"
1010
"explo/src/models"
1111
"explo/src/util"
1212
)
@@ -263,7 +263,7 @@ func (c *ListenBrainz) getImportPlaylist(user string) (string, error) { // Get u
263263
return id[len(id)-1], nil
264264
}
265265
}
266-
debug.Debug(fmt.Sprintf("playlist output: %v", playlists))
266+
slog.Debug(fmt.Sprintf("playlist output: %v", playlists))
267267
return "", fmt.Errorf("failed to get %s playlist, check if ListenBrainz has generated one this week", c.cfg.ImportPlaylist)
268268
}
269269

0 commit comments

Comments
 (0)