Skip to content

Commit

Permalink
chore: move migration logger to logger package
Browse files Browse the repository at this point in the history
  • Loading branch information
kian99 committed Dec 20, 2024
1 parent 87ab49c commit e65a43c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 19 deletions.
21 changes: 2 additions & 19 deletions internal/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (

"github.com/canonical/jimm/v3/internal/dbmodel"
"github.com/canonical/jimm/v3/internal/errors"
"github.com/canonical/jimm/v3/internal/logger"
)

// Use a custom table name so that we don't run into collisions when OpenFGA or other tools
Expand Down Expand Up @@ -62,24 +63,6 @@ func (d *Database) Transaction(f func(*Database) error) error {
})
}

type migrationLogger struct {
logger *zap.Logger
verbose bool
}

func (l migrationLogger) Printf(format string, v ...interface{}) {
line := fmt.Sprintf(format, v...)
// Remove unneeded new lines since the zap logger adds them.
if line[len(line)-1] == '\n' {
line = line[:len(line)-1]
}
l.logger.Info(line)
}

func (l migrationLogger) Verbose() bool {
return l.verbose
}

// Migrate migrates the configured database to have the structure required
// by the current data model. If the database is not configured then an error
// with a code of errors.CodeServerConfiguration will be returned.
Expand Down Expand Up @@ -125,7 +108,7 @@ func (d *Database) migrateFromSource(ctx context.Context, fs embed.FS, sqlPath s
defer m.Close()

// Setup custom logger for consistent output.
logger := migrationLogger{logger: zapctx.Logger(ctx)}
logger := logger.MigrationLogger{Logger: zapctx.Logger(ctx)}
m.Log = logger

if err := d.handleDeprecatedMigrations(ctx, m); err != nil {
Expand Down
30 changes: 30 additions & 0 deletions internal/logger/migration_logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright 2024 Canonical.

package logger

import (
"fmt"

"go.uber.org/zap"
)

// MigrationLogger provides a logger for use with DB migrations.
type MigrationLogger struct {
Logger *zap.Logger
IsVerbose bool
}

// Printf implements the Printf function of the migrate.Logger interface.
func (l MigrationLogger) Printf(format string, v ...interface{}) {
line := fmt.Sprintf(format, v...)
// Remove unneeded new lines since the zap logger adds them.
if line[len(line)-1] == '\n' {
line = line[:len(line)-1]
}
l.Logger.Info(line)
}

// Verbose implements the Verbose function of the migrate.Logger interface.
func (l MigrationLogger) Verbose() bool {
return l.IsVerbose
}

0 comments on commit e65a43c

Please sign in to comment.