gin 自定义日志输出

  • 2022-06-28
  • 浏览 (583)

首先说下gin.Default()和gin.New()的区别

gin.Defualt


func Default() *Engine {
	debugPrintWARNINGDefault()
	engine := New()
	engine.Use(Logger(), Recovery())
	return engine
}

gin.Nex

func New() *Engine {
	debugPrintWARNINGNew()
	engine := &Engine{
		RouterGroup: RouterGroup{
			Handlers: nil,
			basePath: "/",
			root:     true,
		},
		FuncMap:                template.FuncMap{},
		RedirectTrailingSlash:  true,
		RedirectFixedPath:      false,
		HandleMethodNotAllowed: false,
		ForwardedByClientIP:    true,
		RemoteIPHeaders:        []string{"X-Forwarded-For", "X-Real-IP"},
		TrustedPlatform:        defaultPlatform,
		UseRawPath:             false,
		RemoveExtraSlash:       false,
		UnescapePathValues:     true,
		MaxMultipartMemory:     defaultMultipartMemory,
		trees:                  make(methodTrees, 0, 9),
		delims:                 render.Delims{Left: "{{", Right: "}}"},
		secureJSONPrefix:       "while(1);",
		trustedProxies:         []string{"0.0.0.0/0"},
		trustedCIDRs:           defaultTrustedCIDRs,
	}
	engine.RouterGroup.engine = engine
	engine.pool.New = func() interface{} {
		return engine.allocateContext()
	}
	return engine
}

gin.New()gin.Default()都是初始化一个Engine实例,gin.Default()里面调用了gin.New(),在调用完gin.New()得到Engine实例后,还调用了engine.Use(Logger(), Recovery());gin.Default()获取到的Engine实例集成了LoggerRecovery中间件,gin.New() 返回一个新的空白Engine实例,没有附加任何中间件。

使用自定义的日志输出

从上面的代码可以看出,要使用自定义的日志输出,需要使用gin.New(),然后设置自己的日志中间件。

Router := gin.New()

Router.Use(gin.Recovery())

Router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
  if utils.IsNotEmpty(param.Path) && strings.Contains(param.Path, "static") {
  	return ""
  }

  return fmt.Sprintf("ip:%s, time:[%s], proto:%s, status:%d, latency:%s, agent:%s, method:%s, path:%s, err:%s \n",
          param.ClientIP,
          param.TimeStamp.Format(time.RFC3339),
          param.Request.Proto,
          param.StatusCode,
          param.Latency,
          param.Request.UserAgent(),
          param.Method,
          param.Path,
          param.ErrorMessage,
  )
}))