loglevel.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package apiutil
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "github.com/julienschmidt/httprouter"
  7. "github.com/opencost/opencost/core/pkg/log"
  8. )
  9. type LogLevelRequestResponse struct {
  10. Level string `json:"level"`
  11. }
  12. func GetLogLevel(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  13. w.Header().Set("Content-Type", "application/json")
  14. w.Header().Set("Access-Control-Allow-Origin", "*")
  15. level := log.GetLogLevel()
  16. llrr := LogLevelRequestResponse{
  17. Level: level,
  18. }
  19. body, err := json.Marshal(llrr)
  20. if err != nil {
  21. http.Error(w, fmt.Sprintf("unable to retrive log level"), http.StatusInternalServerError)
  22. return
  23. }
  24. _, err = w.Write(body)
  25. if err != nil {
  26. http.Error(w, fmt.Sprintf("unable to write response: %s", body), http.StatusInternalServerError)
  27. return
  28. }
  29. }
  30. func SetLogLevel(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  31. params := LogLevelRequestResponse{}
  32. err := json.NewDecoder(r.Body).Decode(&params)
  33. if err != nil {
  34. http.Error(w, fmt.Sprintf("unable to decode request body, error: %s", err), http.StatusBadRequest)
  35. return
  36. }
  37. err = log.SetLogLevel(params.Level)
  38. if err != nil {
  39. http.Error(w, fmt.Sprintf("level must be a valid log level according to zerolog; level given: %s, error: %s", params.Level, err), http.StatusBadRequest)
  40. return
  41. }
  42. w.WriteHeader(http.StatusOK)
  43. }