Skip to content

Commit ae60be0

Browse files
committed
tapdb: add support for logging migrations
In this commit, we add support for logging migrations as they happen. This is useful for users to keep track of what happens during a `tapd` update.
1 parent 58bfe28 commit ae60be0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

tapdb/migrations.go

+34
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"net/http"
99
"strings"
1010

11+
"github.com/btcsuite/btclog"
1112
"github.com/golang-migrate/migrate/v4"
1213
"github.com/golang-migrate/migrate/v4/database"
1314
"github.com/golang-migrate/migrate/v4/source/httpfs"
@@ -33,6 +34,36 @@ var (
3334
}
3435
)
3536

37+
// migrationLogger is a logger that wraps the passed btclog.Logger so it can be
38+
// used to log migrations.
39+
type migrationLogger struct {
40+
log btclog.Logger
41+
}
42+
43+
// Printf is like fmt.Printf. We map this to the target logger based on the
44+
// current log level.
45+
func (m *migrationLogger) Printf(format string, v ...interface{}) {
46+
switch m.log.Level() {
47+
case btclog.LevelTrace:
48+
m.log.Tracef(format, v...)
49+
case btclog.LevelDebug:
50+
m.log.Debugf(format, v...)
51+
case btclog.LevelInfo:
52+
m.log.Infof(format, v...)
53+
case btclog.LevelWarn:
54+
m.log.Warnf(format, v...)
55+
case btclog.LevelError:
56+
m.log.Errorf(format, v...)
57+
case btclog.LevelCritical:
58+
m.log.Criticalf(format, v...)
59+
}
60+
}
61+
62+
// Verbose should return true when verbose logging output is wanted
63+
func (m *migrationLogger) Verbose() bool {
64+
return m.log.Level() <= btclog.LevelDebug
65+
}
66+
3667
// applyMigrations executes database migration files found in the given file
3768
// system under the given path, using the passed database driver and database
3869
// name, up to or down to the given target version.
@@ -58,6 +89,9 @@ func applyMigrations(fs fs.FS, driver database.Driver, path, dbName string,
5889
return err
5990
}
6091

92+
// Apply our local logger to the migration instance.
93+
sqlMigrate.Log = &migrationLogger{log}
94+
6195
// Execute the migration based on the target given.
6296
err = targetVersion(sqlMigrate)
6397
if err != nil && !errors.Is(err, migrate.ErrNoChange) {

0 commit comments

Comments
 (0)