Add DEBUG log_level.
All checks were successful
Build Docker image / build (push) Successful in 1m35s
Build Golang packages / release (push) Successful in 2m4s

This commit is contained in:
Pieter Hollander 2024-07-27 00:08:40 +02:00
parent 48d0382b0e
commit b63c1e85d3
Signed by: pieter
SSH key fingerprint: SHA256:HbX+9cBXsop9SuvL+mELd29sK+7DehFfdVweFVDtMSg

31
main.go
View file

@ -156,6 +156,7 @@ type Config struct {
OpenDTUPassword string `json:"opendtu_password"`
TimescaleDB bool `json:"timescaledb"`
TZ string `json:"tz"`
LogLevel string `json:"log_level"`
}
var logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
@ -240,6 +241,30 @@ func loadConfig() Config {
return config
}
// Helper function to map environment variable to slog.Level
func getLogLevel(defaultLevel slog.Level) slog.Level {
logLevelStr := config.LogLevel
switch logLevelStr {
case "DEBUG":
return slog.LevelDebug
case "INFO":
return slog.LevelInfo
case "WARN":
return slog.LevelWarn
case "ERROR":
return slog.LevelError
default:
return defaultLevel
}
}
// Function to create a new logger with a specified log level
func createLoggerWithLevel(level slog.Level) *slog.Logger {
return slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: level,
}))
}
// Main program
func main() {
// Initial logger setup
@ -248,6 +273,10 @@ func main() {
// Load the configuration
config := loadConfig()
// Set the logLevel
logLevel := getLogLevel(slog.LevelInfo) // Default to info level
logger = createLoggerWithLevel(logLevel)
dbConnStr := config.DB
// Connect to PostgreSQL
db, err := sql.Open("postgres", dbConnStr)
@ -262,6 +291,8 @@ func main() {
// Create WebSocket URL from config variable
wsURL := "ws://" + config.OpenDTUAddress + "/livedata"
logger.Debug(wsURL)
// Create headers with optional Basic Auth
headers := http.Header{}
if config.OpenDTUAuth {