使用zap日志替代xorm日志

xorm提供了自定义日志的接口,它的接口定义如下:

// Logger is a logger interface
type Logger interface {
	Debug(v ...interface{})
	Debugf(format string, v ...interface{})
	Error(v ...interface{})
	Errorf(format string, v ...interface{})
	Info(v ...interface{})
	Infof(format string, v ...interface{})
	Warn(v ...interface{})
	Warnf(format string, v ...interface{})

	Level() LogLevel
	SetLevel(l LogLevel)

	ShowSQL(show ...bool)
	IsShowSQL() bool
}

也就是说我们可以自己实现这些接口,用自己的日志框架啊替代原生的日志框架

下面是我用zap实现该接口的代码

type ZapLogger struct {
	logger  *zap.SugaredLogger
	showSQL bool
	level   log.LogLevel
}

func NewZapLogger(logger *zap.SugaredLogger) *ZapLogger {
	return &ZapLogger{
		logger:  logger,
		showSQL: false,
		level:   log.LOG_INFO,
	}
}
func (c *ZapLogger) Debug(v ...interface{}) {
	if !c.showSQL || c.level > log.LOG_DEBUG {
		return
	}
	c.logger.Debug(v)
}
func (c *ZapLogger) Debugf(format string, v ...interface{}) {
	if !c.showSQL || c.level > log.LOG_DEBUG {
		return
	}
	c.logger.Debugf(format, v)
}
func (c *ZapLogger) Info(v ...interface{}) {
	if !c.showSQL || c.level > log.LOG_INFO {
		return
	}
	c.logger.Info(v)
}
func (c *ZapLogger) Infof(format string, v ...interface{}) {
	if !c.showSQL || c.level > log.LOG_INFO {
		return
	}
	c.logger.Infof(format, v)
}
func (c *ZapLogger) Warn(v ...interface{}) {
	if !c.showSQL || c.level > log.LOG_WARNING {
		return
	}
	c.logger.Warn(v)
}
func (c *ZapLogger) Warnf(format string, v ...interface{}) {
	if !c.showSQL || c.level > log.LOG_WARNING {
		return
	}
	c.logger.Warnf(format, v)
}
func (c *ZapLogger) Error(v ...interface{}) {
	if !c.showSQL || c.level > log.LOG_ERR {
		return
	}
	c.logger.Error(v)
}
func (c *ZapLogger) Errorf(format string, v ...interface{}) {
	if !c.showSQL || c.level > log.LOG_ERR {
		return
	}
	c.logger.Errorf(format, v)
}

func (c *ZapLogger) IsShowSQL() bool {
	return c.showSQL
}
func (c *ZapLogger) ShowSQL(show ...bool) {
	c.showSQL = show[0]
}
func (c *ZapLogger) SetLevel(l log.LogLevel) {
	c.level = l
}

func (c *ZapLogger) Level() log.LogLevel {
	return c.level
}

这段代码实现了xorm.logger接口

直接在engine出调用SetLogger即可

你可能感兴趣的:(golang,go,xorm,zap)