增加日志记录器记录sql语句

pull/23/head
taoshihan1991 4 years ago
parent d0a274096c
commit 562df437c1

@ -8,6 +8,7 @@ import (
"github.com/taoshihan1991/imaptool/config"
"github.com/taoshihan1991/imaptool/docs"
"github.com/taoshihan1991/imaptool/router"
"github.com/taoshihan1991/imaptool/tools"
"log"
"os"
"os/exec"
@ -56,6 +57,8 @@ func run() {
engine.LoadHTMLGlob("static/html/*")
engine.Static("/static", "./static")
//记录日志
engine.Use(tools.LoggerToFile())
router.InitViewRouter(engine)
router.InitApiRouter(engine)

@ -19,6 +19,7 @@ require (
github.com/ipipdotnet/ipdb-go v1.3.0
github.com/jinzhu/gorm v1.9.14
github.com/satori/go.uuid v1.2.0
github.com/sirupsen/logrus v1.4.2
github.com/spf13/cobra v0.0.5
github.com/swaggo/gin-swagger v1.2.0
github.com/swaggo/swag v1.5.1

@ -4,6 +4,7 @@ import (
"fmt"
"github.com/jinzhu/gorm"
"github.com/taoshihan1991/imaptool/config"
"github.com/taoshihan1991/imaptool/tools"
"time"
)
@ -26,6 +27,7 @@ func init() {
}
DB.SingularTable(true)
DB.LogMode(true)
DB.SetLogger(tools.Logger())
DB.DB().SetMaxIdleConns(10)
DB.DB().SetMaxOpenConns(100)

@ -46,6 +46,10 @@ func (obj *CommonHtml) Display(file string, data interface{}) {
//首页
func PageIndex(c *gin.Context) {
if c.Request.RequestURI == "/favicon.ico" {
return
}
lang, _ := c.Get("lang")
language := config.CreateLanguage(lang.(string))
about := models.FindAboutByPageLanguage("index", lang.(string))

@ -0,0 +1,87 @@
package tools
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"os"
"path"
"time"
)
func Logger() *logrus.Logger {
now := time.Now()
logFilePath := ""
if dir, err := os.Getwd(); err == nil {
logFilePath = dir + "/logs/"
}
if err := os.MkdirAll(logFilePath, 0777); err != nil {
fmt.Println(err.Error())
}
logFileName := now.Format("2006-01-02") + ".log"
//日志文件
fileName := path.Join(logFilePath, logFileName)
if _, err := os.Stat(fileName); err != nil {
if _, err := os.Create(fileName); err != nil {
fmt.Println(err.Error())
}
}
//写入文件
src, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
fmt.Println("err", err)
}
//实例化
logger := logrus.New()
//设置输出
logger.Out = src
//设置日志级别
logger.SetLevel(logrus.DebugLevel)
//设置日志格式
logger.SetFormatter(&logrus.TextFormatter{
TimestampFormat: "2006-01-02 15:04:05",
})
return logger
}
func LoggerToFile() gin.HandlerFunc {
logger := Logger()
return func(c *gin.Context) {
// 开始时间
startTime := time.Now()
// 处理请求
c.Next()
// 结束时间
endTime := time.Now()
// 执行时间
latencyTime := endTime.Sub(startTime)
// 请求方式
reqMethod := c.Request.Method
// 请求路由
reqUri := c.Request.RequestURI
// 状态码
statusCode := c.Writer.Status()
// 请求IP
clientIP := c.ClientIP()
//日志格式
logger.Infof("| %3d | %13v | %15s | %s | %s |",
statusCode,
latencyTime,
clientIP,
reqMethod,
reqUri,
)
}
}
Loading…
Cancel
Save