change logging flags

This commit is contained in:
Joel Wetzell
2025-12-29 16:07:56 -06:00
parent 3ef41d0026
commit 710dcf3a02
2 changed files with 45 additions and 11 deletions

2
.vscode/launch.json vendored
View File

@@ -11,7 +11,7 @@
"request": "launch", "request": "launch",
"mode": "auto", "mode": "auto",
"program": "cmd/showbridge", "program": "cmd/showbridge",
"args": ["--debug"], "args": ["--log-level", "debug"],
"cwd": "./" "cwd": "./"
} }
] ]

View File

@@ -3,9 +3,11 @@ package main
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"log/slog" "log/slog"
"os" "os"
"os/signal" "os/signal"
"slices"
"sync" "sync"
"github.com/jwetzell/showbridge-go" "github.com/jwetzell/showbridge-go"
@@ -29,15 +31,29 @@ func main() {
Value: "./config.yaml", Value: "./config.yaml",
Usage: "path to config file", Usage: "path to config file",
}, },
&cli.BoolFlag{ &cli.StringFlag{
Name: "debug", Name: "log-level",
Value: false, Value: "debug",
Usage: "set log level to DEBUG", Usage: "set log level to DEBUG",
Validator: func(level string) error {
levels := []string{"debug", "info", "warn", "error"}
if !slices.Contains(levels, level) {
return fmt.Errorf("unknown log level: %s", level)
}
return nil
},
}, },
&cli.BoolFlag{ &cli.StringFlag{
Name: "json", Name: "log-format",
Value: false, Value: "text",
Usage: "log using JSON", Usage: "log format to use",
Validator: func(format string) error {
formats := []string{"text", "json"}
if !slices.Contains(formats, format) {
return fmt.Errorf("unknown log format: %s", format)
}
return nil
},
}, },
}, },
Action: run, Action: run,
@@ -83,8 +99,19 @@ func run(ctx context.Context, c *cli.Command) error {
logLevel := slog.LevelInfo logLevel := slog.LevelInfo
if c.Bool("debug") { logLevelFromFlag := c.String("log-level")
switch logLevelFromFlag {
case "debug":
logLevel = slog.LevelDebug logLevel = slog.LevelDebug
case "info":
logLevel = slog.LevelInfo
case "warn":
logLevel = slog.LevelWarn
case "error":
logLevel = slog.LevelError
default:
logLevel = slog.LevelInfo
} }
logHandlerOptions := &slog.HandlerOptions{ logHandlerOptions := &slog.HandlerOptions{
@@ -93,10 +120,17 @@ func run(ctx context.Context, c *cli.Command) error {
logOutput := os.Stderr logOutput := os.Stderr
var logHandler slog.Handler = slog.NewTextHandler(logOutput, logHandlerOptions) var logHandler slog.Handler
if c.Bool("json") { logFormat := c.String("log-format")
switch logFormat {
case "json":
logHandler = slog.NewJSONHandler(logOutput, logHandlerOptions) logHandler = slog.NewJSONHandler(logOutput, logHandlerOptions)
case "text":
logHandler = slog.NewTextHandler(logOutput, logHandlerOptions)
default:
logHandler = slog.NewTextHandler(logOutput, logHandlerOptions)
} }
slog.SetDefault(slog.New(logHandler)) slog.SetDefault(slog.New(logHandler))