Skip to content

Commit

Permalink
Merge pull request lightninglabs#772 from lightninglabs/log-migration
Browse files Browse the repository at this point in the history
tapdb: add support for logging migrations
  • Loading branch information
Roasbeef authored Jan 26, 2024
2 parents 58bfe28 + afd69ee commit cd916e7
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions tapdb/migrations.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http"
"strings"

"github.com/btcsuite/btclog"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database"
"github.com/golang-migrate/migrate/v4/source/httpfs"
Expand All @@ -33,6 +34,39 @@ var (
}
)

// migrationLogger is a logger that wraps the passed btclog.Logger so it can be
// used to log migrations.
type migrationLogger struct {
log btclog.Logger
}

// Printf is like fmt.Printf. We map this to the target logger based on the
// current log level.
func (m *migrationLogger) Printf(format string, v ...interface{}) {
// Trim trailing newlines from the format.
format = strings.TrimRight(format, "\n")

switch m.log.Level() {
case btclog.LevelTrace:
m.log.Tracef(format, v...)
case btclog.LevelDebug:
m.log.Debugf(format, v...)
case btclog.LevelInfo:
m.log.Infof(format, v...)
case btclog.LevelWarn:
m.log.Warnf(format, v...)
case btclog.LevelError:
m.log.Errorf(format, v...)
case btclog.LevelCritical:
m.log.Criticalf(format, v...)
}
}

// Verbose should return true when verbose logging output is wanted
func (m *migrationLogger) Verbose() bool {
return m.log.Level() <= btclog.LevelDebug
}

// applyMigrations executes database migration files found in the given file
// system under the given path, using the passed database driver and database
// name, up to or down to the given target version.
Expand All @@ -58,6 +92,13 @@ func applyMigrations(fs fs.FS, driver database.Driver, path, dbName string,
return err
}

migrationVersion, _, _ := sqlMigrate.Version()

log.Infof("Applying migrations from version=%v", migrationVersion)

// Apply our local logger to the migration instance.
sqlMigrate.Log = &migrationLogger{log}

// Execute the migration based on the target given.
err = targetVersion(sqlMigrate)
if err != nil && !errors.Is(err, migrate.ErrNoChange) {
Expand Down

0 comments on commit cd916e7

Please sign in to comment.