Skip to content

Commit 9dbe5ee

Browse files
committed
Finish migration to log/slog
Signed-off-by: Marcus Crane <[email protected]>
1 parent f4fcd27 commit 9dbe5ee

10 files changed

+167
-83
lines changed

backend/db.go

-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package backend
22

33
import (
44
"github.com/glebarez/sqlite"
5-
"github.com/sirupsen/logrus"
65
"gorm.io/gorm"
76
)
87

@@ -11,7 +10,6 @@ var Conn *gorm.DB
1110
func OpenConnection(filepath string) error {
1211
conn, err := gorm.Open(sqlite.Open(filepath), &gorm.Config{})
1312
if err != nil {
14-
logrus.WithError(err).WithField("filepath", filepath).Error("Failed to open DB connection")
1513
return err
1614
}
1715
Conn = conn

backend/device.go

+38-19
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,9 @@ package backend
22

33
import (
44
"fmt"
5+
"log/slog"
56
"strings"
67

7-
"github.com/sirupsen/logrus"
8-
98
"github.com/pgaskin/koboutils/v2/kobo"
109
)
1110

@@ -155,14 +154,20 @@ func (Bookmark) TableName() string {
155154
return "Bookmark"
156155
}
157156

158-
func GetKoboMetadata(detectedPaths []string) []Kobo {
157+
func GetKoboMetadata(detectedPaths []string, logger *slog.Logger) []Kobo {
159158
var kobos []Kobo
160159
for _, path := range detectedPaths {
161160
_, _, deviceId, err := kobo.ParseKoboVersion(path)
162161
if err != nil {
163-
logrus.WithField("kobo_path", path).WithError(err).Error("Failed to parse Kobo version")
162+
logger.Error("Failed to parse Kobo version",
163+
slog.String("error", err.Error()),
164+
slog.String("kobo_path", path),
165+
)
164166
}
165-
logrus.WithField("device_id", deviceId).Info("Found an attached device")
167+
logger.Info("Found attached device",
168+
slog.String("device_id", deviceId),
169+
slog.String("kobo_path", path),
170+
)
166171
device, found := kobo.DeviceByID(deviceId)
167172
if found {
168173
kobos = append(kobos, Kobo{
@@ -187,7 +192,9 @@ func GetKoboMetadata(detectedPaths []string) []Kobo {
187192
})
188193
continue
189194
}
190-
logrus.WithField("device_id", deviceId).Warn("Found a device that isn't officially supported but will likely still operate just fine")
195+
logger.Warn("Found a device that isn't officially supported but will likely still operate just fine",
196+
slog.String("device_id", deviceId),
197+
)
191198
// We can handle unsupported Kobos in future but at present, there are none
192199
kobos = append(kobos, Kobo{
193200
MntPath: path,
@@ -197,55 +204,67 @@ func GetKoboMetadata(detectedPaths []string) []Kobo {
197204
return kobos
198205
}
199206

200-
func (k *Kobo) ListDeviceContent(includeStoreBought bool) ([]Content, error) {
207+
func (k *Kobo) ListDeviceContent(includeStoreBought bool, logger *slog.Logger) ([]Content, error) {
201208
var content []Content
202-
logrus.Debug("Retrieving content list from device")
209+
logger.Debug("Retrieving content list from device")
203210
result := Conn.Where(&Content{ContentType: "6", VolumeIndex: -1})
204211
if !includeStoreBought {
205212
result = result.Where("ContentID LIKE '%file:///%'")
206213
}
207214
result = result.Order("___PercentRead desc, title asc").Find(&content)
208215
if result.Error != nil {
209-
logrus.WithError(result.Error).Error("Failed to retrieve content from device")
216+
logger.Error("Failed to retrieve content from device",
217+
slog.String("error", result.Error.Error()),
218+
)
210219
return nil, result.Error
211220
}
212-
logrus.WithField("content_count", len(content)).Debug("Successfully retrieved device content")
221+
logger.Debug("Successfully retrieved device content",
222+
slog.Int("content_count", len(content)),
223+
)
213224
return content, nil
214225
}
215226

216-
func (k *Kobo) ListDeviceBookmarks(includeStoreBought bool) ([]Bookmark, error) {
227+
func (k *Kobo) ListDeviceBookmarks(includeStoreBought bool, logger *slog.Logger) ([]Bookmark, error) {
217228
var bookmarks []Bookmark
218-
logrus.Debug("Retrieving bookmarks from device")
229+
logger.Debug("Retrieving bookmarks from device")
219230
result := Conn
220231
if !includeStoreBought {
221232
result = result.Where("VolumeID LIKE '%file:///%'")
222233
}
223234
result = result.Order("VolumeID ASC, ChapterProgress ASC").Find(&bookmarks).Limit(1)
224235
if result.Error != nil {
225-
logrus.WithError(result.Error).Error("Failed to retrieve bookmarks from device")
236+
logger.Error("Failed to retrieve bookmarks from device",
237+
slog.String("error", result.Error.Error()),
238+
)
226239
return nil, result.Error
227240
}
228-
logrus.WithField("bookmark_count", len(bookmarks)).Debug("Successfully retrieved device bookmarks")
241+
logger.Debug("Successfully retrieved device bookmarks",
242+
slog.Int("bookmark_count", len(bookmarks)),
243+
)
229244
return bookmarks, nil
230245
}
231246

232-
func (k *Kobo) BuildContentIndex(content []Content) map[string]Content {
233-
logrus.Debug("Building an index out of device content")
247+
func (k *Kobo) BuildContentIndex(content []Content, logger *slog.Logger) map[string]Content {
248+
logger.Debug("Building an index out of device content")
234249
contentIndex := make(map[string]Content)
235250
for _, item := range content {
236251
contentIndex[item.ContentID] = item
237252
}
238-
logrus.WithField("index_count", len(contentIndex)).Debug("Built content index")
253+
logger.Debug("Built content index",
254+
slog.Int("index_count", len(contentIndex)),
255+
)
239256
return contentIndex
240257
}
241258

242-
func (k *Kobo) CountDeviceBookmarks() HighlightCounts {
259+
func (k *Kobo) CountDeviceBookmarks(logger *slog.Logger) HighlightCounts {
243260
var totalCount int64
244261
var officialCount int64
245262
var sideloadedCount int64
246263
result := Conn.Model(&Bookmark{}).Count(&totalCount)
247264
if result.Error != nil {
248-
logrus.WithError(result.Error).Error("Failed to count bookmarks on device")
265+
logger.Error("Failed to count bookmarks on device",
266+
slog.String("error", result.Error.Error()),
267+
)
249268
}
250269
Conn.Model(&Bookmark{}).Where("VolumeID LIKE '%file:///%'").Count(&sideloadedCount)
251270
Conn.Model(&Bookmark{}).Where("VolumeID NOT LIKE '%file:///%'").Count(&officialCount)

backend/device_test.go

+5-7
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
package backend
22

33
import (
4+
"log/slog"
45
"os"
56
"path/filepath"
67
"testing"
78

8-
"github.com/sirupsen/logrus"
99
"github.com/stretchr/testify/assert"
1010
)
1111

@@ -22,20 +22,18 @@ func setupTmpKobo(dir string, deviceId string) string {
2222
content := []byte(deviceId)
2323
err := os.Mkdir(filepath.Join(dir, ".kobo"), 0777)
2424
if err != nil {
25-
logrus.Fatal(err)
26-
return ""
25+
panic(err)
2726
}
2827
tmpfn := filepath.Join(dir, ".kobo", "version")
2928
if err := os.WriteFile(tmpfn, content, 0666); err != nil {
30-
logrus.Fatal(err)
31-
return ""
29+
panic(err)
3230
}
3331
return dir
3432
}
3533

3634
func TestGetKoboMetadata_HandleNoDevices(t *testing.T) {
3735
var expected []Kobo
38-
actual := GetKoboMetadata([]string{})
36+
actual := GetKoboMetadata([]string{}, slog.New(&discardHandler{}))
3937
assert.Equal(t, expected, actual)
4038
}
4139

@@ -85,6 +83,6 @@ func TestGetKoboMetadata_HandleConnectedDevices(t *testing.T) {
8583
},
8684
}
8785
detectedPaths := []string{fakeLibraVolume, fakeMiniVolume, fakeElipsaVolume, fakeClara2EVolume, fakeUnknownVolume}
88-
actual := GetKoboMetadata(detectedPaths)
86+
actual := GetKoboMetadata(detectedPaths, slog.New(&discardHandler{}))
8987
assert.Equal(t, expected, actual)
9088
}

backend/init.go

+11-6
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ func StartBackend(ctx *context.Context, version string, portable bool, logger *s
5151
RuntimeContext: ctx,
5252
Settings: settings,
5353
Readwise: &Readwise{
54+
logger: logger,
5455
UserAgent: fmt.Sprintf(UserAgentFmt, version),
5556
},
5657
Kobo: &Kobo{},
@@ -122,7 +123,7 @@ func (b *Backend) DetectKobos() []Kobo {
122123
b.logger.Error("Failed to detect any connected Kobos")
123124
panic(err)
124125
}
125-
kobos := GetKoboMetadata(connectedKobos)
126+
kobos := GetKoboMetadata(connectedKobos, b.logger)
126127
b.logger.Info("Found one or more kobos",
127128
"count", len(kobos),
128129
)
@@ -159,6 +160,10 @@ func (b *Backend) SelectKobo(devicePath string) error {
159160
}
160161
}
161162
if err := OpenConnection(b.SelectedKobo.DbPath); err != nil {
163+
b.logger.Error("Failed to open DB connection",
164+
slog.String("error", err.Error()),
165+
slog.String("db_path", b.SelectedKobo.DbPath),
166+
)
162167
return err
163168
}
164169
return nil
@@ -185,7 +190,7 @@ func (b *Backend) PromptForLocalDBPath() error {
185190
}
186191

187192
func (b *Backend) ForwardToReadwise() (int, error) {
188-
highlightBreakdown := b.Kobo.CountDeviceBookmarks()
193+
highlightBreakdown := b.Kobo.CountDeviceBookmarks(b.logger)
189194
slog.Info("Got highlight counts from device",
190195
slog.Int("highlight_count_sideload", int(highlightBreakdown.Sideloaded)),
191196
slog.Int("highlight_count_official", int(highlightBreakdown.Official)),
@@ -200,22 +205,22 @@ func (b *Backend) ForwardToReadwise() (int, error) {
200205
slog.Error("Tried to submit highlights with no sideloaded highlights + store-bought syncing disabled. Result is that no highlights would be fetched.")
201206
return 0, fmt.Errorf("You have disabled store-bought syncing but you don't have any sideloaded highlights either. This combination means there are no highlights left to be synced.")
202207
}
203-
content, err := b.Kobo.ListDeviceContent(includeStoreBought)
208+
content, err := b.Kobo.ListDeviceContent(includeStoreBought, b.logger)
204209
if err != nil {
205210
slog.Error("Received an error trying to list content from device",
206211
slog.String("error", err.Error()),
207212
)
208213
return 0, err
209214
}
210-
contentIndex := b.Kobo.BuildContentIndex(content)
211-
bookmarks, err := b.Kobo.ListDeviceBookmarks(includeStoreBought)
215+
contentIndex := b.Kobo.BuildContentIndex(content, b.logger)
216+
bookmarks, err := b.Kobo.ListDeviceBookmarks(includeStoreBought, b.logger)
212217
if err != nil {
213218
slog.Error("Received an error trying to list bookmarks from device",
214219
slog.String("error", err.Error()),
215220
)
216221
return 0, err
217222
}
218-
payload, err := BuildPayload(bookmarks, contentIndex)
223+
payload, err := BuildPayload(bookmarks, contentIndex, b.logger)
219224
if err != nil {
220225
slog.Error("Received an error trying to build Readwise payload",
221226
slog.String("error", err.Error()),

backend/log.go

+8-4
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
package backend
22

33
import (
4+
"context"
45
"fmt"
56
"log/slog"
67
"os"
78
"time"
8-
9-
"github.com/sirupsen/logrus"
109
)
1110

1211
var logFileHandle *os.File
@@ -18,8 +17,6 @@ func StartLogger(portable bool, level slog.Leveler) (*slog.Logger, error) {
1817
if err != nil {
1918
panic("Failed to create location to store logfiles")
2019
}
21-
22-
logrus.SetFormatter(&logrus.JSONFormatter{})
2320
file, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2421
if err != nil {
2522
return &slog.Logger{}, err
@@ -35,3 +32,10 @@ func StartLogger(portable bool, level slog.Leveler) (*slog.Logger, error) {
3532
func CloseLogFile() {
3633
logFileHandle.Close()
3734
}
35+
36+
// Dummy until real handler ships in Go 1.24
37+
type discardHandler struct {
38+
slog.TextHandler
39+
}
40+
41+
func (d *discardHandler) Enabled(context.Context, slog.Level) bool { return false }

0 commit comments

Comments
 (0)