Skip to content

Commit d2dce96

Browse files
committed
feat: consolidate logging
1 parent dc9f202 commit d2dce96

File tree

15 files changed

+121
-95
lines changed

15 files changed

+121
-95
lines changed

ap/ap.go

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ import (
3131
const pongAckInterval = 120 * time.Second
3232

3333
type Accesspoint struct {
34+
log *log.Entry
35+
3436
addr librespot.GetAddressFunc
3537

3638
nonce []byte
@@ -57,8 +59,8 @@ type Accesspoint struct {
5759
welcome *pb.APWelcome
5860
}
5961

60-
func NewAccesspoint(addr librespot.GetAddressFunc, deviceId string) *Accesspoint {
61-
return &Accesspoint{addr: addr, deviceId: deviceId, recvChans: make(map[PacketType][]chan Packet)}
62+
func NewAccesspoint(log *log.Entry, addr librespot.GetAddressFunc, deviceId string) *Accesspoint {
63+
return &Accesspoint{log: log, addr: addr, deviceId: deviceId, recvChans: make(map[PacketType][]chan Packet)}
6264
}
6365

6466
func (ap *Accesspoint) init(ctx context.Context) (err error) {
@@ -85,14 +87,14 @@ func (ap *Accesspoint) init(ctx context.Context) (err error) {
8587
// we assign to ap.conn after because if Dial fails we'll have a nil ap.conn which we don't want
8688
ap.conn = conn
8789
// Successfully connected.
88-
log.Debugf("connected to %s", addr)
90+
ap.log.Debugf("connected to %s", addr)
8991
return nil
9092
} else if attempts >= 6 {
9193
// Only try a few times before giving up.
9294
return fmt.Errorf("failed to connect to AP %v: %w", addr, err)
9395
}
9496
// Try again with a different AP.
95-
log.WithError(err).Warnf("failed to connect to AP %v, retrying with a different AP", addr)
97+
ap.log.WithError(err).Warnf("failed to connect to AP %v, retrying with a different AP", addr)
9698
}
9799
}
98100

@@ -249,7 +251,7 @@ func (ap *Accesspoint) Receive(types ...PacketType) <-chan Packet {
249251

250252
func (ap *Accesspoint) startReceiving() {
251253
ap.recvLoopOnce.Do(func() {
252-
log.Tracef("starting accesspoint recv loop")
254+
ap.log.Tracef("starting accesspoint recv loop")
253255
go ap.recvLoop()
254256

255257
// set last ping in the future
@@ -268,19 +270,22 @@ loop:
268270
// no need to hold the connMu since reconnection happens in this routine
269271
pkt, payload, err := ap.encConn.receivePacket(context.TODO())
270272
if err != nil {
271-
log.WithError(err).Errorf("failed receiving packet")
273+
if !ap.stop {
274+
ap.log.WithError(err).Errorf("failed receiving packet")
275+
}
276+
272277
break loop
273278
}
274279

275280
switch pkt {
276281
case PacketTypePing:
277-
log.Tracef("received accesspoint ping")
282+
ap.log.Tracef("received accesspoint ping")
278283
if err := ap.encConn.sendPacket(context.TODO(), PacketTypePong, payload); err != nil {
279-
log.WithError(err).Errorf("failed sending Pong packet")
284+
ap.log.WithError(err).Errorf("failed sending Pong packet")
280285
break loop
281286
}
282287
case PacketTypePongAck:
283-
log.Tracef("received accesspoint pong ack")
288+
ap.log.Tracef("received accesspoint pong ack")
284289
ap.lastPongAckLock.Lock()
285290
ap.lastPongAck = time.Now()
286291
ap.lastPongAckLock.Unlock()
@@ -297,7 +302,7 @@ loop:
297302
}
298303

299304
if !handled {
300-
log.Debugf("skipping packet %v, len: %d", pkt, len(payload))
305+
ap.log.Debugf("skipping packet %v, len: %d", pkt, len(payload))
301306
}
302307
}
303308
}
@@ -310,7 +315,7 @@ loop:
310315
if !ap.stop {
311316
ap.connMu.Lock()
312317
if err := backoff.Retry(ap.reconnect, backoff.NewExponentialBackOff()); err != nil {
313-
log.WithError(err).Errorf("failed reconnecting accesspoint, bye bye")
318+
ap.log.WithError(err).Errorf("failed reconnecting accesspoint, bye bye")
314319
log.Exit(1)
315320
}
316321
ap.connMu.Unlock()
@@ -347,7 +352,7 @@ loop:
347352
timePassed := time.Since(ap.lastPongAck)
348353
ap.lastPongAckLock.Unlock()
349354
if timePassed > pongAckInterval {
350-
log.Errorf("did not receive last pong ack from accesspoint, %.0fs passed", timePassed.Seconds())
355+
ap.log.Errorf("did not receive last pong ack from accesspoint, %.0fs passed", timePassed.Seconds())
351356

352357
// closing the connection should make the read on the "recvLoop" fail,
353358
// continue hoping for a new connection
@@ -376,7 +381,7 @@ func (ap *Accesspoint) reconnect() (err error) {
376381
// if we are here the "recvLoop" has already died, restart it
377382
go ap.recvLoop()
378383

379-
log.Debugf("re-established accesspoint connection")
384+
ap.log.Debugf("re-established accesspoint connection")
380385
return nil
381386
}
382387

@@ -426,7 +431,7 @@ func (ap *Accesspoint) performKeyExchange() ([]byte, error) {
426431
// exchange keys and compute shared secret
427432
ap.dh.Exchange(apResponse.Challenge.LoginCryptoChallenge.DiffieHellman.Gs)
428433

429-
log.Debugf("completed keyexchange")
434+
ap.log.Debugf("completed keyexchange")
430435
return cc.Dump(), nil
431436
}
432437

@@ -463,7 +468,7 @@ func (ap *Accesspoint) solveChallenge(exchangeData []byte) error {
463468
var resp pb.APResponseMessage
464469
if err := readMessage(ap.conn, &resp); errors.Is(err, os.ErrDeadlineExceeded) {
465470
ap.encConn = newShannonConn(ap.conn, macData[20:52], macData[52:84])
466-
log.Debug("completed challenge")
471+
ap.log.Debug("completed challenge")
467472
return nil
468473
} else if err != nil {
469474
return fmt.Errorf("failed reading APLoginFailed message: %w", err)
@@ -510,7 +515,7 @@ func (ap *Accesspoint) authenticate(ctx context.Context, credentials *pb.LoginCr
510515
}
511516

512517
ap.welcome = &welcome
513-
log.Infof("authenticated AP as %s", *welcome.CanonicalUsername)
518+
ap.log.Infof("authenticated AP as %s", *welcome.CanonicalUsername)
514519

515520
return nil
516521
} else if recvPkt == PacketTypeAuthFailure {

apresolve/resolve.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ type apResolveResponse struct {
2121
}
2222

2323
type ApResolver struct {
24+
log *log.Entry
25+
2426
baseUrl *url.URL
2527

2628
endpoints map[endpointType][]string
@@ -30,13 +32,14 @@ type ApResolver struct {
3032
client *http.Client
3133
}
3234

33-
func NewApResolver(client *http.Client) *ApResolver {
35+
func NewApResolver(log *log.Entry, client *http.Client) *ApResolver {
3436
baseUrl, err := url.Parse("https://apresolve.spotify.com/")
3537
if err != nil {
3638
panic("invalid apresolve base URL")
3739
}
3840

3941
return &ApResolver{
42+
log: log,
4043
baseUrl: baseUrl,
4144
client: client,
4245
endpoints: map[endpointType][]string{},
@@ -100,17 +103,17 @@ func (r *ApResolver) fetchUrls(ctx context.Context, types ...endpointType) error
100103
if slices.Contains(types, endpointTypeAccesspoint) {
101104
r.endpoints[endpointTypeAccesspoint] = respJson.Accesspoint
102105
r.endpointsExp[endpointTypeAccesspoint] = time.Now().Add(1 * time.Hour)
103-
log.Debugf("fetched new accesspoints: %v", respJson.Accesspoint)
106+
r.log.Debugf("fetched new accesspoints: %v", respJson.Accesspoint)
104107
}
105108
if slices.Contains(types, endpointTypeDealer) {
106109
r.endpoints[endpointTypeDealer] = respJson.Dealer
107110
r.endpointsExp[endpointTypeDealer] = time.Now().Add(1 * time.Hour)
108-
log.Debugf("fetched new dealers: %v", respJson.Dealer)
111+
r.log.Debugf("fetched new dealers: %v", respJson.Dealer)
109112
}
110113
if slices.Contains(types, endpointTypeSpclient) {
111114
r.endpoints[endpointTypeSpclient] = respJson.Spclient
112115
r.endpointsExp[endpointTypeSpclient] = time.Now().Add(1 * time.Hour)
113-
log.Debugf("fetched new spclients: %v", respJson.Spclient)
116+
r.log.Debugf("fetched new spclients: %v", respJson.Spclient)
114117
}
115118

116119
return nil
@@ -155,7 +158,7 @@ func (r *ApResolver) getFunc(ctx context.Context, type_ endpointType) (librespot
155158
newAddrs, err := r.get(innerCtx, type_)
156159
if err != nil {
157160
// if we cannot fetch new endpoints, eat it and return the first one
158-
log.WithError(err).Warnf("failed fetching new endpoint for %s", type_)
161+
r.log.WithError(err).Warnf("failed fetching new endpoint for %s", type_)
159162
return addrs[0]
160163
}
161164

cmd/daemon/controls.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ func (p *AppPlayer) handlePlayerEvent(ctx context.Context, ev *player.Event) {
140140
type skipToFunc func(*connectpb.ContextTrack) bool
141141

142142
func (p *AppPlayer) loadContext(ctx context.Context, spotCtx *connectpb.Context, skipTo skipToFunc, paused, drop bool) error {
143-
ctxTracks, err := tracks.NewTrackListFromContext(ctx, p.sess.Spclient(), spotCtx)
143+
ctxTracks, err := tracks.NewTrackListFromContext(ctx, p.app.log, p.sess.Spclient(), spotCtx)
144144
if err != nil {
145145
return fmt.Errorf("failed creating track list: %w", err)
146146
}

cmd/daemon/main.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import (
3636
var errAlreadyRunning = errors.New("go-librespot is already running")
3737

3838
type App struct {
39+
log *log.Entry
3940
cfg *Config
4041

4142
client *http.Client
@@ -64,6 +65,7 @@ func parseDeviceType(val string) (devicespb.DeviceType, error) {
6465
func NewApp(cfg *Config) (app *App, err error) {
6566
app = &App{cfg: cfg, logoutCh: make(chan *AppPlayer)}
6667

68+
app.log = log.NewEntry(log.StandardLogger())
6769
app.client = &http.Client{}
6870

6971
app.deviceType, err = parseDeviceType(cfg.DeviceType)
@@ -75,7 +77,7 @@ func NewApp(cfg *Config) (app *App, err error) {
7577
return nil, err
7678
}
7779

78-
app.resolver = apresolve.NewApResolver(app.client)
80+
app.resolver = apresolve.NewApResolver(app.log, app.client)
7981

8082
if cfg.DeviceId != "" {
8183
// Use configured device ID.
@@ -118,6 +120,7 @@ func (app *App) newAppPlayer(ctx context.Context, creds any) (_ *AppPlayer, err
118120
appPlayer.prefetchTimer = time.AfterFunc(time.Duration(math.MaxInt64), appPlayer.prefetchNext)
119121

120122
if appPlayer.sess, err = session.NewSessionFromOptions(ctx, &session.Options{
123+
Log: app.log,
121124
DeviceType: app.deviceType,
122125
DeviceId: app.deviceId,
123126
ClientToken: app.clientToken,
@@ -230,7 +233,7 @@ func (app *App) withAppPlayer(ctx context.Context, appPlayerFunc func(context.Co
230233
}
231234

232235
// start zeroconf server and dispatch
233-
z, err := zeroconf.NewZeroconf(app.cfg.ZeroconfPort, app.cfg.DeviceName, app.deviceId, app.deviceType)
236+
z, err := zeroconf.NewZeroconf(app.log, app.cfg.ZeroconfPort, app.cfg.DeviceName, app.deviceId, app.deviceType)
234237
if err != nil {
235238
return fmt.Errorf("failed initializing zeroconf: %w", err)
236239
}

cmd/daemon/player.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ func (p *AppPlayer) handlePlayerCommand(ctx context.Context, req dealer.RequestP
159159
}
160160
p.state.lastTransferTimestamp = transferState.Playback.Timestamp
161161

162-
ctxTracks, err := tracks.NewTrackListFromContext(ctx, p.sess.Spclient(), transferState.CurrentSession.Context)
162+
ctxTracks, err := tracks.NewTrackListFromContext(ctx, p.app.log, p.sess.Spclient(), transferState.CurrentSession.Context)
163163
if err != nil {
164164
return fmt.Errorf("failed creating track list: %w", err)
165165
}

dealer/dealer.go

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ const (
2121
)
2222

2323
type Dealer struct {
24+
log *log.Entry
25+
2426
client *http.Client
2527

2628
addr librespot.GetAddressFunc
@@ -46,14 +48,15 @@ type Dealer struct {
4648
requestReceiversLock sync.RWMutex
4749
}
4850

49-
func NewDealer(client *http.Client, dealerAddr librespot.GetAddressFunc, accessToken librespot.GetLogin5TokenFunc) *Dealer {
51+
func NewDealer(log *log.Entry, client *http.Client, dealerAddr librespot.GetAddressFunc, accessToken librespot.GetLogin5TokenFunc) *Dealer {
5052
return &Dealer{
5153
client: &http.Client{
5254
Transport: client.Transport,
5355
CheckRedirect: client.CheckRedirect,
5456
Jar: client.Jar,
5557
Timeout: timeout,
5658
},
59+
log: log,
5760
addr: dealerAddr,
5861
accessToken: accessToken,
5962
requestReceivers: map[string]requestReceiver{},
@@ -65,7 +68,7 @@ func (d *Dealer) Connect(ctx context.Context) error {
6568
defer d.connMu.Unlock()
6669

6770
if d.conn != nil && !d.stop {
68-
log.Debugf("dealer connection already opened")
71+
d.log.Debugf("dealer connection already opened")
6972
return nil
7073
}
7174

@@ -97,7 +100,7 @@ func (d *Dealer) connect(ctx context.Context) error {
97100
// remove the read limit
98101
d.conn.SetReadLimit(math.MaxUint32)
99102

100-
log.Debugf("dealer connection opened")
103+
d.log.Debugf("dealer connection opened")
101104

102105
return nil
103106
}
@@ -119,7 +122,7 @@ func (d *Dealer) Close() {
119122

120123
func (d *Dealer) startReceiving() {
121124
d.recvLoopOnce.Do(func() {
122-
log.Tracef("starting dealer recv loop")
125+
d.log.Tracef("starting dealer recv loop")
123126
go d.recvLoop()
124127

125128
// set last pong in the future
@@ -141,7 +144,7 @@ loop:
141144
timePassed := time.Since(d.lastPong)
142145
d.lastPongLock.Unlock()
143146
if timePassed > pingInterval+timeout {
144-
log.Errorf("did not receive last pong from dealer, %.0fs passed", timePassed.Seconds())
147+
d.log.Errorf("did not receive last pong from dealer, %.0fs passed", timePassed.Seconds())
145148

146149
// closing the connection should make the read on the "recvLoop" fail,
147150
// continue hoping for a new connection
@@ -154,15 +157,15 @@ loop:
154157
err := d.conn.Write(ctx, websocket.MessageText, []byte("{\"type\":\"ping\"}"))
155158
d.connMu.RUnlock()
156159
cancel()
157-
log.Tracef("sent dealer ping")
160+
d.log.Tracef("sent dealer ping")
158161

159162
if err != nil {
160163
if d.stop {
161164
// break early without logging if we should stop
162165
break loop
163166
}
164167

165-
log.WithError(err).Warnf("failed sending dealer ping")
168+
d.log.WithError(err).Warnf("failed sending dealer ping")
166169

167170
// closing the connection should make the read on the "recvLoop" fail,
168171
// continue hoping for a new connection
@@ -187,19 +190,19 @@ loop:
187190

188191
// don't log closed error if we're stopping
189192
if d.stop && websocket.CloseStatus(err) == websocket.StatusGoingAway {
190-
log.Debugf("dealer connection closed")
193+
d.log.Debugf("dealer connection closed")
191194
break loop
192195
} else if err != nil {
193-
log.WithError(err).Errorf("failed receiving dealer message")
196+
d.log.WithError(err).Errorf("failed receiving dealer message")
194197
break loop
195198
} else if msgType != websocket.MessageText {
196-
log.WithError(err).Warnf("unsupported message type: %v, len: %d", msgType, len(messageBytes))
199+
d.log.WithError(err).Warnf("unsupported message type: %v, len: %d", msgType, len(messageBytes))
197200
continue
198201
}
199202

200203
var message RawMessage
201204
if err := json.Unmarshal(messageBytes, &message); err != nil {
202-
log.WithError(err).Error("failed unmarshalling dealer message")
205+
d.log.WithError(err).Error("failed unmarshalling dealer message")
203206
break loop
204207
}
205208

@@ -217,10 +220,10 @@ loop:
217220
d.lastPongLock.Lock()
218221
d.lastPong = time.Now()
219222
d.lastPongLock.Unlock()
220-
log.Tracef("received dealer pong")
223+
d.log.Tracef("received dealer pong")
221224
break
222225
default:
223-
log.Warnf("unknown dealer message type: %s", message.Type)
226+
d.log.Warnf("unknown dealer message type: %s", message.Type)
224227
break
225228
}
226229
}
@@ -233,7 +236,7 @@ loop:
233236
if !d.stop {
234237
d.connMu.Lock()
235238
if err := backoff.Retry(d.reconnect, backoff.NewExponentialBackOff()); err != nil {
236-
log.WithError(err).Errorf("failed reconnecting dealer, bye bye")
239+
d.log.WithError(err).Errorf("failed reconnecting dealer, bye bye")
237240
log.Exit(1)
238241
}
239242
d.connMu.Unlock()
@@ -254,7 +257,7 @@ loop:
254257
}
255258
d.messageReceiversLock.RUnlock()
256259

257-
log.Debugf("dealer recv loop stopped")
260+
d.log.Debugf("dealer recv loop stopped")
258261
}
259262

260263
func (d *Dealer) sendReply(key string, success bool) error {
@@ -289,6 +292,6 @@ func (d *Dealer) reconnect() error {
289292
// restart the recv loop
290293
go d.recvLoop()
291294

292-
log.Debugf("re-established dealer connection")
295+
d.log.Debugf("re-established dealer connection")
293296
return nil
294297
}

0 commit comments

Comments
 (0)