嵌入 logrus
最后更新于:2022-04-02 02:47:36
[TOC]
## xorm > 1.0
1.0 可输出完整的sql 字符串
```
package db
import (
"github.com/sirupsen/logrus"
"xorm.io/xorm/log"
)
type dbLog struct {
logger *logrus.Logger
showSQL bool
}
func NewDbLog(showSQL bool) *dbLog {
return &dbLog{
showSQL: showSQL,
logger:logrus.StandardLogger(),
}
}
func (d *dbLog) BeforeSQL(context log.LogContext) {
d.logger.Infof("BeforeSQL : %+v\n", context.SQL)
}
func (d *dbLog) AfterSQL(context log.LogContext) {
d.logger.Infof("AfterSQL : %+v\n", context.SQL)
}
func (d *dbLog) Debugf(format string, v ...interface{}) {
d.logger.Debugf(format, v)
}
func (d *dbLog) Errorf(format string, v ...interface{}) {
d.logger.Errorf(format, v)
}
func (d *dbLog) Infof(format string, v ...interface{}) {
d.logger.Infof(format, v)
}
func (d *dbLog) Warnf(format string, v ...interface{}) {
d.logger.Warnf(format, v)
}
func (d *dbLog) Level() log.LogLevel {
return log.LogLevel(d.logger.Level)
}
func (d *dbLog) SetLevel(l log.LogLevel) {
d.logger.SetLevel(logrus.Level(l))
}
func (d *dbLog) ShowSQL(show ...bool) {
if len(show) == 0 {
d.showSQL = true
return
}
d.showSQL = show[0]
}
func (d *dbLog) IsShowSQL() bool {
return d.showSQL
}
```
使用
```
engine, _:= xorm.NewEngine(dbtype, dsn)
...
newDbLog := NewDbLog(conf.DB.ShowSql)
engine.SetLogger(newDbLog)
```
';