gin 自定义日志输出
首先说下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
实例集成了Logger
和Recovery
中间件,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,
)
}))
0
赞
热门推荐
-
2、 - 优质文章
-
3、 gate.io
-
8、 golang
-
9、 openharmony
-
10、 Vue中input框自动聚焦