Skip to content

Commit

Permalink
refactor: refine get logger from context
Browse files Browse the repository at this point in the history
  • Loading branch information
elliotxx committed Nov 28, 2023
1 parent 7de3da2 commit f0e1f8a
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 11 deletions.
13 changes: 4 additions & 9 deletions pkg/apis/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,18 @@ import (
"net/http"

"github.com/KusionStack/karbour/pkg/controller/config"
"github.com/KusionStack/karbour/pkg/middleware"
"k8s.io/klog/v2"
"github.com/KusionStack/karbour/pkg/util/ctxutil"
)

func Get(configCtrl *config.Controller) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
logger, ok := r.Context().Value(middleware.APILoggerKey).(klog.Logger)
if !ok {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
log := ctxutil.GetLogger(r.Context())

logger.Info("Starting get config ...")
log.Info("Starting get config ...")

b, err := json.MarshalIndent(configCtrl.Get(), "", " ")
if err != nil {
logger.Error(err, "Failed to mashal json")
log.Error(err, "Failed to mashal json")
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/apiserver/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ func NewCoreAPIs() http.Handler {
r.Use(appmiddleware.APILogger)
r.Use(middleware.Recoverer)

// Set up frontend router
// Set up the frontend router
klog.Infof("Dashboard's static directory use: %s", DefaultStaticDirectory)
r.NotFound(http.FileServer(http.Dir(DefaultStaticDirectory)).ServeHTTP)

// Set up core api router
// Set up the core api router
configCtrl := config.NewController(&config.Config{
Verbose: false,
})
Expand Down
21 changes: 21 additions & 0 deletions pkg/util/ctxutil/ctxutil.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package ctxutil

import (
"context"

"github.com/KusionStack/karbour/pkg/middleware"
"k8s.io/klog/v2"
)

// GetLogger returns the logger from the given context.
//
// Example:
//
// logger := ctxutil.GetLogger(ctx)
func GetLogger(ctx context.Context) klog.Logger {
if logger, ok := ctx.Value(middleware.APILoggerKey).(klog.Logger); ok {
return logger
}

return klog.NewKlogr()
}

0 comments on commit f0e1f8a

Please sign in to comment.