Skip to content

Commit cd916e7

Browse files
authored
Merge pull request #772 from lightninglabs/log-migration
tapdb: add support for logging migrations
2 parents 58bfe28 + afd69ee commit cd916e7

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

tapdb/migrations.go

Lines changed: 41 additions & 0 deletions
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,39 @@ 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+
// Trim trailing newlines from the format.
47+
format = strings.TrimRight(format, "\n")
48+
49+
switch m.log.Level() {
50+
case btclog.LevelTrace:
51+
m.log.Tracef(format, v...)
52+
case btclog.LevelDebug:
53+
m.log.Debugf(format, v...)
54+
case btclog.LevelInfo:
55+
m.log.Infof(format, v...)
56+
case btclog.LevelWarn:
57+
m.log.Warnf(format, v...)
58+
case btclog.LevelError:
59+
m.log.Errorf(format, v...)
60+
case btclog.LevelCritical:
61+
m.log.Criticalf(format, v...)
62+
}
63+
}
64+
65+
// Verbose should return true when verbose logging output is wanted
66+
func (m *migrationLogger) Verbose() bool {
67+
return m.log.Level() <= btclog.LevelDebug
68+
}
69+
3670
// applyMigrations executes database migration files found in the given file
3771
// system under the given path, using the passed database driver and database
3872
// name, up to or down to the given target version.
@@ -58,6 +92,13 @@ func applyMigrations(fs fs.FS, driver database.Driver, path, dbName string,
5892
return err
5993
}
6094

95+
migrationVersion, _, _ := sqlMigrate.Version()
96+
97+
log.Infof("Applying migrations from version=%v", migrationVersion)
98+
99+
// Apply our local logger to the migration instance.
100+
sqlMigrate.Log = &migrationLogger{log}
101+
61102
// Execute the migration based on the target given.
62103
err = targetVersion(sqlMigrate)
63104
if err != nil && !errors.Is(err, migrate.ErrNoChange) {

0 commit comments

Comments
 (0)