diff --git a/pkg/apis/config/config.go b/pkg/apis/config/config.go index 8a8d05ec..001e43b6 100644 --- a/pkg/apis/config/config.go +++ b/pkg/apis/config/config.go @@ -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 } diff --git a/pkg/apiserver/router.go b/pkg/apiserver/router.go index d640ffc0..6656d3ee 100644 --- a/pkg/apiserver/router.go +++ b/pkg/apiserver/router.go @@ -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, }) diff --git a/pkg/util/ctxutil/ctxutil.go b/pkg/util/ctxutil/ctxutil.go new file mode 100644 index 00000000..20f54afe --- /dev/null +++ b/pkg/util/ctxutil/ctxutil.go @@ -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() +}