给 Chi 路由器添加日志记录功能

huangapple go评论93阅读模式
英文:

Adding logging to Chi router

问题

我正在尝试使用httplog为使用oapi-codegen生成的Chi服务设置日志记录,但结构化日志没有显示在控制台上。当我使用fmt.Println时,我可以在控制台上看到这些语句。

oapi-codegen的config.yaml如下所示:

package: main
generate:
  chi-server: true
  embedded-spec: true
  models: true

以下是我迄今为止尝试过的内容:

main.go中,我们有:

func main() {
	s, err := NewAccountServer(myAwesomeConnectionString)
	if err != nil {
		panic(err)
	}

	logger := httplog.NewLogger("httplog-example", httplog.Options{
		JSON: true,
	})

	r := chi.NewRouter()
	r.Use(middleware.RequestID)
	r.Use(httplog.RequestLogger(logger))
	r.Use(middleware.Recoverer)

	h := Handler(s)
	r.Mount("/", h)

	var server = &http.Server{
		Handler: h,
		Addr:    "0.0.0.0:3000",
	}
	log.Fatal(server.ListenAndServe())
}

这将启动服务器,并且能够正常提供请求。以下是一个示例处理程序:

func (a AccountServer) GetAccountsEmail(w http.ResponseWriter, r *http.Request, params GetAccountsEmailParams) {
	oplog := httplog.LogEntry(r.Context())
	oplog.Debug().Msgf("Finding user by ID ", params.AccountId.String())
	prefs, err := a.db.GetByAccountId(context.TODO(), params.AccountId)
	if err != nil {
		oplog.Debug().Err(err)
		w.Write([]byte(err.Error()))
	}

    oplog.Debug().Msgf("Found them!")
	prefsJson, err := json.Marshal(prefs)
	if err != nil {
		oplog.Info().Err(err)
		w.Write([]byte(err.Error()))
	}
	oplog.Info().Msg(string(prefsJson))
	w.Write(prefsJson)
}
英文:

I'm attempting to set up logging using httplog for a Chi service that was generated with oapi-codegen, but structured logging isn't showing up in the console. When I use fmt.Println I can see those statements in the console.

The oapi-codegen config.yaml looks like this:

package: main
generate:
  chi-server: true
  embedded-spec: true
  models: true

Here's what I've tried thus far:

In main.go, we have:

func main() {
	s, err := NewAccountServer(myAwesomeConnectionString)
	if err != nil {
		panic(err)
	}

	logger := httplog.NewLogger("httplog-example", httplog.Options{
		JSON: true,
	})

	r := chi.NewRouter()
	r.Use(middleware.RequestID)
	r.Use(httplog.RequestLogger(logger))
	r.Use(middleware.Recoverer)

	h := Handler(s)
	r.Mount("/", h)

	var server = &http.Server{
		Handler: h,
		Addr:    "0.0.0.0:3000",
	}
	log.Fatal(server.ListenAndServe())
}

This stands up the server and it's able to serve requests just fine. Here's an example handler:

func (a AccountServer) GetAccountsEmail(w http.ResponseWriter, r *http.Request, params GetAccountsEmailParams) {
	oplog := httplog.LogEntry(r.Context())
	oplog.Debug().Msgf("Finding user by ID ", params.AccountId.String())
	prefs, err := a.db.GetByAccountId(context.TODO(), params.AccountId)
	if err != nil {
		oplog.Debug().Err(err)
		w.Write([]byte(err.Error()))
	}

    oplog.Debug().Msgf("Found them!")
	prefsJson, err := json.Marshal(prefs)
	if err != nil {
		oplog.Info().Err(err)
		w.Write([]byte(err.Error()))
	}
	oplog.Info().Msg(string(prefsJson))
	w.Write(prefsJson)
}

答案1

得分: 1

关键是重新阅读宠物商店应用程序的示例代码

我做错了什么?我没有正确设置处理程序。而不是

h := Handler(s)
r.Mount("/", h)

var server = &http.Server{
    Handler: h,
    Addr:    "0.0.0.0:3000",
}

我需要做的是:

HandlerFromMux(s, r)

var server = &http.Server{
	Handler: r,
	Addr:    "0.0.0.0:3000",
}
log.Fatal(server.ListenAndServe())
英文:

The trick was to re-read the example code for the petstore application.

Where did I go wrong? I wasn't setting up the handler correctly. Instead of

h := Handler(s)
r.Mount("/", h)

var server = &http.Server{
    Handler: h,
    Addr:    "0.0.0.0:3000",
}

I needed to do:

HandlerFromMux(s, r)

var server = &http.Server{
	Handler: r,
	Addr:    "0.0.0.0:3000",
}
log.Fatal(server.ListenAndServe())

huangapple
  • 本文由 发表于 2022年8月29日 20:50:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/73529084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定