Skip to content

Commit

Permalink
Add interface to the Logger
Browse files Browse the repository at this point in the history
  • Loading branch information
ybkuroki committed Feb 23, 2022
1 parent b61a5f9 commit e566b2f
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 27 deletions.
8 changes: 4 additions & 4 deletions container/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,20 @@ import (
type Container interface {
GetRepository() repository.Repository
GetConfig() *config.Config
GetLogger() *logger.Logger
GetLogger() logger.Logger
GetEnv() string
}

// container struct is for sharing data which such as database setting, the setting of application and logger in overall this application.
type container struct {
rep repository.Repository
config *config.Config
logger *logger.Logger
logger logger.Logger
env string
}

// NewContainer is constructor.
func NewContainer(rep repository.Repository, config *config.Config, logger *logger.Logger, env string) Container {
func NewContainer(rep repository.Repository, config *config.Config, logger logger.Logger, env string) Container {
return &container{rep: rep, config: config, logger: logger, env: env}
}

Expand All @@ -38,7 +38,7 @@ func (c *container) GetConfig() *config.Config {
}

// GetLogger returns the object of logger.
func (c *container) GetLogger() *logger.Logger {
func (c *container) GetLogger() logger.Logger {
return c.logger
}

Expand Down
16 changes: 8 additions & 8 deletions logger/gormlogger.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,39 +22,39 @@ const (
)

// LogMode: The log level of gorm logger is overwrited by the log level of Zap logger.
func (l *Logger) LogMode(level gormLogger.LogLevel) gormLogger.Interface {
func (l *logger) LogMode(level gormLogger.LogLevel) gormLogger.Interface {
return l
}

// Info prints a information log.
func (l *Logger) Info(ctx context.Context, msg string, data ...interface{}) {
func (l *logger) Info(ctx context.Context, msg string, data ...interface{}) {
l.Zap.Infof(messageFormat, append([]interface{}{msg, gormUtils.FileWithLineNum()}, data...)...)
}

// Warn prints a warning log.
func (l *Logger) Warn(ctx context.Context, msg string, data ...interface{}) {
func (l *logger) Warn(ctx context.Context, msg string, data ...interface{}) {
l.Zap.Warnf(messageFormat, append([]interface{}{msg, gormUtils.FileWithLineNum()}, data...)...)
}

// Error prints a error log.
func (l *Logger) Error(ctx context.Context, msg string, data ...interface{}) {
func (l *logger) Error(ctx context.Context, msg string, data ...interface{}) {
l.Zap.Errorf(messageFormat, append([]interface{}{msg, gormUtils.FileWithLineNum()}, data...)...)
}

// Trace prints a trace log such as sql, source file and error.
func (l *Logger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
func (l *logger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
elapsed := time.Since(begin)

switch {
case err != nil:
sql, _ := fc()
l.Zap.Errorf(errorFormat, gormUtils.FileWithLineNum(), err, sql)
l.GetZapLogger().Errorf(errorFormat, gormUtils.FileWithLineNum(), err, sql)
case elapsed > slowThreshold*time.Millisecond && slowThreshold*time.Millisecond != 0:
sql, _ := fc()
slowLog := fmt.Sprintf("SLOW SQL >= %v", slowThreshold)
l.Zap.Warnf(errorFormat, gormUtils.FileWithLineNum(), slowLog, sql)
l.GetZapLogger().Warnf(errorFormat, gormUtils.FileWithLineNum(), slowLog, sql)
default:
sql, _ := fc()
l.Zap.Debugf(sqlFormat, sql)
l.GetZapLogger().Debugf(sqlFormat, sql)
}
}
31 changes: 24 additions & 7 deletions logger/logger.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package logger

import (
"context"
"fmt"
"io/ioutil"
"os"
"time"

"go.uber.org/zap"
"gopkg.in/natefinch/lumberjack.v2"
"gopkg.in/yaml.v2"
gormLogger "gorm.io/gorm/logger"
)

// Config represents the setting for zap logger.
Expand All @@ -17,12 +20,26 @@ type Config struct {
}

// Logger is an alternative implementation of *gorm.Logger
type Logger struct {
type Logger interface {
GetZapLogger() *zap.SugaredLogger
LogMode(level gormLogger.LogLevel) gormLogger.Interface
Info(ctx context.Context, msg string, data ...interface{})
Warn(ctx context.Context, msg string, data ...interface{})
Error(ctx context.Context, msg string, data ...interface{})
Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)
}

type logger struct {
Zap *zap.SugaredLogger
}

// NewLogger create logger object for *gorm.DB from *echo.Logger
func NewLogger(env string) *Logger {
// NewLogger is constructor for logger
func NewLogger(sugar *zap.SugaredLogger) Logger {
return &logger{Zap: sugar}
}

// InitLogger create logger object for *gorm.DB from *echo.Logger
func InitLogger(env string) Logger {
configYaml, err := ioutil.ReadFile("./zaplogger." + env + ".yml")
if err != nil {
fmt.Printf("Failed to read logger configuration: %s", err)
Expand All @@ -41,13 +58,13 @@ func NewLogger(env string) *Logger {
}
sugar := zap.Sugar()
// set package varriable logger.
logger := &Logger{Zap: sugar}
logger.Zap.Infof("Success to read zap logger configuration: zaplogger." + env + ".yml")
log := NewLogger(sugar)
log.GetZapLogger().Infof("Success to read zap logger configuration: zaplogger." + env + ".yml")
_ = zap.Sync()
return logger
return log
}

// GetZapLogger returns zapSugaredLogger
func (log *Logger) GetZapLogger() *zap.SugaredLogger {
func (log *logger) GetZapLogger() *zap.SugaredLogger {
return log.Zap
}
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func main() {
e := echo.New()

conf, env := config.Load()
logger := logger.NewLogger(env)
logger := logger.InitLogger(env)
logger.GetZapLogger().Infof("Loaded this configuration : application." + env + ".yml")

rep := repository.NewBookRepository(logger, conf)
Expand Down
4 changes: 2 additions & 2 deletions repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ type bookRepository struct {
}

// NewBookRepository is constructor for bookRepository.
func NewBookRepository(logger *logger.Logger, conf *config.Config) Repository {
func NewBookRepository(logger logger.Logger, conf *config.Config) Repository {
logger.GetZapLogger().Infof("Try database connection")
db, err := connectDatabase(logger, conf)
if err != nil {
Expand All @@ -66,7 +66,7 @@ const (
MYSQL = "mysql"
)

func connectDatabase(logger *logger.Logger, config *config.Config) (*gorm.DB, error) {
func connectDatabase(logger logger.Logger, config *config.Config) (*gorm.DB, error) {
var dsn string
gormConfig := &gorm.Config{Logger: logger}

Expand Down
10 changes: 5 additions & 5 deletions test/unittest_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,32 +75,32 @@ func createConfig(isSecurity bool) *config.Config {
return conf
}

func initContainer(conf *config.Config, logger *logger.Logger) container.Container {
func initContainer(conf *config.Config, logger logger.Logger) container.Container {
rep := repository.NewBookRepository(logger, conf)
container := container.NewContainer(rep, conf, logger, "test")
return container
}

func initTestLogger() *logger.Logger {
func initTestLogger() logger.Logger {
myConfig := createLoggerConfig()
zap, err := myConfig.Build()
if err != nil {
fmt.Printf("Error")
}
sugar := zap.Sugar()
// set package varriable logger.
logger := &logger.Logger{Zap: sugar}
logger := logger.NewLogger(sugar)
logger.GetZapLogger().Infof("Success to read zap logger configuration")
_ = zap.Sync()
return logger
}

func initObservedLogger() (*logger.Logger, *observer.ObservedLogs) {
func initObservedLogger() (logger.Logger, *observer.ObservedLogs) {
observedZapCore, observedLogs := observer.New(zap.DebugLevel)
sugar := zap.New(observedZapCore).Sugar()

// set package varriable logger.
logger := &logger.Logger{Zap: sugar}
logger := logger.NewLogger(sugar)
return logger, observedLogs
}

Expand Down

0 comments on commit e566b2f

Please sign in to comment.