使用 zap 替换 xorm 的日志系统

zap 是 uber 开发的快速日志。

使用 https://github.com/yxlimo/xormzap 这个简易的适配器即可

代码如下:

log.go 工具类

package util

import "go.uber.org/zap"

var logger *zap.Logger

func Log() *zap.Logger {
    if logger != nil {
        return logger
    }
    g, _ := zap.NewProduction()

    logger = g
    return logger
}

func L() *zap.SugaredLogger {
    if logger != nil {
        return logger.Sugar()
    }
    return Log().Sugar()
}

repo.go 基于 xorm 的简陋封装

package repo

import (
    "fmt"

    _ "github.com/go-sql-driver/mysql"
    "github.com/yxlimo/xormzap"
    "xorm.io/xorm"
    "xorm.io/xorm/names"
    "yujinping.top/pams/util"
)

var engine *xorm.Engine

func Repo() *xorm.Engine {
    if engine != nil {
        return engine
    }
    var err error
    username := "root"
    password := ""
    host := "localhost"
    port := 3306
    database := "test"
    url := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port, database)

    engine, err = xorm.NewEngine("mysql", url)
    if err != nil {
        panic("Cannot link to the database")
    }

  // 使用xormzap适配器,传入 util.Log()实例,并设置为engine的Logger
    logger := xormzap.Logger(util.Log())
    engine.SetLogger(logger)

  // 设置 engine 相关配置
    engine.ShowSQL(true)
    engine.SetMaxIdleConns(1000)
    engine.SetMaxOpenConns(1000)
    engine.SetMapper(names.GonicMapper{})
    return engine
}

这样配置完成后,xorm的日志将会变成zap的json格式:

{"level":"info","ts":1655717375.972339,"caller":"xormzap@v0.0.0-20200402025324-807f08df96bd/zap.go:46","msg":"finished sql","sql":"SELECT `id`, `username`, `password`, `real_name`, `avatar`, `create_time` FROM `users` WHERE (username=?) AND (password=?) LIMIT 1 [test 123456]","execute_time":0.074549991}