Skip to content
This repository has been archived by the owner on Nov 27, 2024. It is now read-only.

rest: expose log level as a parameter #153

Merged
merged 1 commit into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions server/config/server/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ spec:
configMapKeyRef:
name: rest-api-server-config
key: kubesaw.namespace
- name: LOG_LEVEL
valueFrom:
configMapKeyRef:
name: rest-api-server-config
key: log.level
- name: WORKSPACES_NAMESPACE
valueFrom:
fieldRef:
Expand Down
2 changes: 2 additions & 0 deletions server/hack/deploy.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ ROOT_DIR="$(realpath "${DIR}"/../..)"
KUBECLI=${KUBECLI:-kubectl}
KUSTOMIZE=${KUSTOMIZE:-kustomize}
YQ=${YQ:-yq}
SERVER_LOG_LEVEL=${SERVER_LOG_LEVEL:-0}

# retrieve toolchain-host namespace
#
Expand Down Expand Up @@ -52,6 +53,7 @@ ${KUSTOMIZE} edit set namespace "$1"
${KUSTOMIZE} edit set image workspaces/rest-api="$2"
${KUSTOMIZE} edit add configmap rest-api-server-config \
--behavior=replace \
--from-literal=log.level="${SERVER_LOG_LEVEL}" \
--from-literal=kubesaw.namespace="${toolchain_host}"

# apply config
Expand Down
30 changes: 25 additions & 5 deletions server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"log/slog"
"os"
"strconv"
"time"

"github.com/go-logr/logr"
Expand All @@ -16,18 +17,17 @@ import (
)

const DefaultAddr string = ":8080"
const EnvLogLevel = "LOG_LEVEL"

func main() {
l := slog.Default()

if err := run(); err != nil {
l := constructLog()
if err := run(l); err != nil {
l.Error("error configuring and running the server", "error", err)
os.Exit(1)
}
}

func run() error {
l := slog.Default()
func run(l *slog.Logger) error {
log.SetLogger(logr.FromSlogHandler(l.Handler()))

// fetch configuration
Expand Down Expand Up @@ -110,3 +110,23 @@ func run() error {

return nil
}

// constructLog constructs a new instance of the logger
func constructLog() *slog.Logger {
logLevel := getLogLevel()

handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: logLevel,
})
return slog.New(handler)
}

// getLogLevel fetches the log level from the appropriate environment variable
func getLogLevel() slog.Level {
env := os.Getenv(EnvLogLevel)
level, err := strconv.Atoi(env)
if err != nil {
return slog.LevelError
}
return slog.Level(level)
}
Loading