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() LogLevelSetLevel(l LogLevel)ShowSQL(show ...bool)IsShowSQL() bool
}
也就是说我们可以自己实现这些接口,用自己的日志框架啊替代原生的日志框架
下面是我用zap实现该接口的代码
type ZapLogger struct {*zap.SugaredLoggershowSQL boollevel log.LogLevel
}func (c *ZapLogger) Warnf(format string, v ...interface{}) {if !c.showSQL || c.level > log.LOG_WARNING {return}c.SugaredLogger.Warnf(format, v)
}func (c *ZapLogger) Infof(format string, v ...interface{}) {if !c.showSQL || c.level > log.LOG_INFO {return}c.SugaredLogger.Infof(format, v)
}func (c *ZapLogger) Errorf(format string, v ...interface{}) {if !c.showSQL || c.level > log.LOG_ERR {return}c.SugaredLogger.Errorf(format, v)
}func (c *ZapLogger) Debugf(format string, v ...interface{}) {if !c.showSQL || c.level > log.LOG_DEBUG {return}c.SugaredLogger.Debugf(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即可