Added log level configurable through env vars.
All checks were successful
Build Docker image / build (push) Successful in 55s

This commit is contained in:
Pieter Hollander 2024-02-20 16:31:51 +01:00
parent 38691f4e85
commit 3986ae1c1e
Signed by: pieter
SSH key fingerprint: SHA256:HbX+9cBXsop9SuvL+mELd29sK+7DehFfdVweFVDtMSg

33
main.go
View file

@ -75,7 +75,32 @@ type Payload struct {
var db *sql.DB
var logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
// Helper function to map environment variable to slog.Level
func getLogLevelFromEnv(defaultLevel slog.Level) slog.Level {
logLevelStr := os.Getenv("LOG_LEVEL")
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,
}))
}
func main() {
// Initial logger setup
slog.SetDefault(logger)
// Load environment variables from .env file if it exists
@ -83,6 +108,14 @@ func main() {
logger.Info("No .env file found or error loading .env file (ignore this message when using container)", "error", err)
}
// Update the logger based on the LOG_LEVEL environment variable
logLevel := getLogLevelFromEnv(slog.LevelInfo) // Default to info level
logger = createLoggerWithLevel(logLevel)
slog.SetDefault(logger) // Update the default logger to the new one with the specified log level
// Example usage of the logger with the new log level
logger.Info("Logger initialized with dynamic log level")
// Connect to PostgreSQL
pgConnStr := os.Getenv("PG_DB")
if err := connectToPostgreSQL(pgConnStr); err != nil {