Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/common-go/log/handler.go
2498 views
1
// Copyright (c) 2020 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package log
6
7
import (
8
"encoding/json"
9
"fmt"
10
"io"
11
"net/http"
12
13
"github.com/sirupsen/logrus"
14
)
15
16
type logLevel struct {
17
Level string `json:"level"`
18
}
19
20
func LevelHandler(w http.ResponseWriter, r *http.Request) {
21
if r.Method == http.MethodGet {
22
reportLogLevel(Log.Logger.Level.String(), w, r)
23
return
24
}
25
26
if r.Method != http.MethodPost && r.Method != http.MethodPut {
27
http.Error(w, r.Method+" unsupported", http.StatusBadRequest)
28
return
29
}
30
31
body, err := io.ReadAll(r.Body)
32
if err != nil {
33
http.Error(w, fmt.Sprintf("cannot decode request: %v", err), http.StatusPreconditionFailed)
34
return
35
}
36
37
if len(body) == 0 {
38
http.Error(w, "invalid request", http.StatusPreconditionFailed)
39
return
40
}
41
42
var req logLevel
43
err = json.Unmarshal(body, &req)
44
if err != nil {
45
http.Error(w, fmt.Sprintf("cannot decode request: %v", err), http.StatusPreconditionFailed)
46
return
47
}
48
49
newLevel, err := logrus.ParseLevel(req.Level)
50
if err != nil {
51
http.Error(w, err.Error(), http.StatusBadRequest)
52
return
53
}
54
55
Log.Logger.SetLevel(newLevel)
56
reportLogLevel(Log.Logger.Level.String(), w, r)
57
}
58
59
func reportLogLevel(level string, w http.ResponseWriter, r *http.Request) {
60
w.Header().Set("Content-Type", "application/json")
61
w.WriteHeader(http.StatusOK)
62
//nolint
63
w.Write([]byte(fmt.Sprintf(`{"level": "%v"}`, level)))
64
}
65
66