Skip to content

Commit

Permalink
tapdb: add support for logging migrations
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Roasbeef committed Jan 26, 2024
1 parent 58bfe28 commit afd69ee
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 afd69ee

Please sign in to comment.