简体   繁体   English

Golang fasthttp 路由器自定义记录器

[英]Golang fasthttp router custom logger

I'm playing with fasthttp and it's router, I have no issues with basic things, I have a working server and a router, that is the easy part.我正在玩 fasthttp 和它的路由器,我对基本的东西没有任何问题,我有一个工作服务器和一个路由器,这是很容易的部分。

The issue is with the logger, I would like to be able to customize that one, but it does not seem possible with the ctx.Logger() as it only takes a Printf argument and the format is not what I'm looking for.问题出在记录器上,我希望能够自定义该记录器,但 ctx.Logger() 似乎不可能,因为它只需要一个 Printf 参数并且格式不是我想要的。

Does anyone knows where in the documentation I can find a working example of what I want to do?有谁知道我可以在文档中的哪里找到我想做的工作示例?

Example of code I currently have:我目前拥有的代码示例:

package server

import (
    "github.com/fasthttp/router"
    "github.com/valyala/fasthttp"
)

// Router will manage the routes of our API server
func Router() *router.Router {
    r := router.New()
    r.GET("/", index)

    return r
}

func index(ctx *fasthttp.RequestCtx) {
    ctx.Logger().Printf("/")
    ctx.WriteString("Welcome!")
}

As I'm still trying my hand with the web servers and I still don't understand some things with it and Go also.由于我仍在尝试使用 web 服务器,但我仍然不了解它和 Go 的某些内容。 So An example would be welcome.所以欢迎举个例子。

For example I would like to be able to do something like that using a logger define in the main package:例如,我希望能够使用主 package 中定义的记录器来执行类似的操作:

 package server

import (
    "github.com/fasthttp/router"
    "github.com/valyala/fasthttp"
    "go.uber.org/zap"
)

// Router will manage the routes of our API server
func Router(loger *zap.Logger) *router.Router {
    r := router.New()
    r.GET("/", index)

    return r
}

func index(ctx *fasthttp.RequestCtx) {
    ctx.Logger().Printf("/") // Here should print in the zap format of my choice.
    ctx.WriteString("Welcome!")
}

If you look at the source code, it's apparent that all you have is the ability to write standard Go-formatted strings:如果您查看源代码,很明显您所拥有的只是编写标准 Go 格式字符串的能力:

func (cl *ctxLogger) Printf(format string, args ...interface{}) {
    msg := fmt.Sprintf(format, args...)
    ctxLoggerLock.Lock()
    cl.logger.Printf("%.3f %s - %s", time.Since(cl.ctx.ConnTime()).Seconds(), cl.ctx.String(), msg)
    ctxLoggerLock.Unlock()
}

The logger simply adds some additional information from the context.记录器只是从上下文中添加一些附加信息。 So further cutomisation beyond the standard Go formatting does not seem possible.因此,超出标准 Go 格式的进一步定制似乎是不可能的。 I'm not sure what "zap format of my choice" is, so I can't say if there's a workaround or even if standard Go formatting options will serve for you here.我不确定“我选择的 zap 格式”是什么,所以我不能说是否有解决方法,或者即使标准 Go 格式选项在这里为您服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM