add logger from context
This commit is contained in:
@@ -1,15 +1,24 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.mak-sim.ru/maksim/observability_2025/internal/logger"
|
||||
"github.com/go-chi/chi/middleware"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/juju/zaputil/zapctx"
|
||||
"go.uber.org/zap"
|
||||
"moul.io/chizap"
|
||||
)
|
||||
|
||||
func someFunc(ctx context.Context) {
|
||||
logger := zapctx.Logger(ctx)
|
||||
time.Sleep(1 * time.Second)
|
||||
logger.Info("Hi from SomeFunc")
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := logger.GetLogger(false)
|
||||
if err != nil {
|
||||
@@ -17,6 +26,8 @@ func main() {
|
||||
}
|
||||
r := chi.NewRouter()
|
||||
|
||||
logger = logger.With(zap.Any("someKey", "someValue"))
|
||||
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(chizap.New(logger, &chizap.Opts{
|
||||
WithReferer: true,
|
||||
@@ -24,6 +35,8 @@ func main() {
|
||||
}))
|
||||
|
||||
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := zapctx.WithLogger(r.Context(), logger)
|
||||
someFunc(ctx)
|
||||
_, err := w.Write([]byte("welcome"))
|
||||
if err != nil {
|
||||
logger.Error("Error writing response", zap.Error(err))
|
||||
@@ -32,4 +45,4 @@ func main() {
|
||||
|
||||
logger.Info("Server started")
|
||||
http.ListenAndServe(":8080", r) //nolint:errcheck
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user