简体   繁体   中英

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.

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.

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. 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 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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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