From 5c3d36592a42c4015dd187e1a120c9d1f7f2ab5e Mon Sep 17 00:00:00 2001 From: gjahn <gregor.jahn@bht-berlin.de> Date: Sat, 25 Nov 2023 00:39:34 +0100 Subject: [PATCH] Add log level configurable via environment variable Available levels for now: debug, error. While the former is the most verbose one and the latter the least verbose. It sets it to 'debug' if in development mode. --- configuration/config.go | 16 ++++++++++++++++ routing/routes.go | 12 ++++++++++++ 2 files changed, 28 insertions(+) diff --git a/configuration/config.go b/configuration/config.go index 2f28320..d0183c2 100644 --- a/configuration/config.go +++ b/configuration/config.go @@ -14,6 +14,8 @@ const BODY_SIZE_LIMIT = 32 * 1024 * 1024 // 32 MB, in bytes type Config struct { Version string `env:"VERSION" envDefault:"N/A"` + LogLevel string `env:"LOG_LEVE" envDefault:"error"` + Environment string `env:"ENV_NAME" envDefault:"development"` Host string `env:"HOST" envDefault:"127.0.0.1"` Port int16 `env:"PORT" envDefault:"3000"` @@ -44,5 +46,19 @@ func New() ( *Config, error ){ ) } + + if cfg.Environment == "development" { cfg.LogLevel = "debug" } + + possibleLogLevels := map[ string ] bool { + "error": true, + "debug": true, + } + if _, ok := possibleLogLevels[ cfg.LogLevel ]; !ok { + return nil, errors.New( + fmt.Sprintf( "Invalid log level: %s", cfg.LogLevel ), + ) + } + + return &cfg, nil } diff --git a/routing/routes.go b/routing/routes.go index 30b607f..0455c76 100644 --- a/routing/routes.go +++ b/routing/routes.go @@ -25,6 +25,18 @@ func SetRoutes( router *f.App, config *configuration.Config, store state.Store, log.Fatal( err ) } + if config.LogLevel == "debug" { + router.All( "*", func( c *f.Ctx ) error { + log.Printf( "%s %s mime:%s agent:%s", + c.Path(), + c.Method(), + c.Get( f.HeaderContentType ), + c.Get( f.HeaderUserAgent ), + ) + return c.Next() + }) + } + router.Get( "/", func( c *f.Ctx ) error { headers := c.GetReqHeaders() -- GitLab