From 8453c48d9e529830e94fa1959e8cb067a36fe33f Mon Sep 17 00:00:00 2001 From: Stavros Date: Thu, 6 Nov 2025 18:11:43 +0200 Subject: [PATCH] feat: add log in json option --- internal/utils/app_utils.go | 20 ++++++++++++++++++++ internal/utils/app_utils_test.go | 18 ++++++++++++++++++ main.go | 6 +++++- 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/internal/utils/app_utils.go b/internal/utils/app_utils.go index 3da6be2..40f48e8 100644 --- a/internal/utils/app_utils.go +++ b/internal/utils/app_utils.go @@ -200,3 +200,23 @@ func GetOAuthProvidersConfig(env []string, args []string, appUrl string) (map[st // Return combined providers return providers, nil } + +func ShoudLogJSON(environ []string, args []string) bool { + for _, e := range environ { + pair := strings.SplitN(e, "=", 2) + if len(pair) == 2 && pair[0] == "LOG_JSON" && strings.ToLower(pair[1]) == "true" { + return true + } + } + + for _, arg := range args[1:] { + if strings.HasPrefix(arg, "--log-json=") { + value := strings.SplitN(arg, "=", 2)[1] + if strings.ToLower(value) == "true" { + return true + } + } + } + + return false +} diff --git a/internal/utils/app_utils_test.go b/internal/utils/app_utils_test.go index c7f8dc3..71c1aa0 100644 --- a/internal/utils/app_utils_test.go +++ b/internal/utils/app_utils_test.go @@ -278,3 +278,21 @@ func TestGetOAuthProvidersConfig(t *testing.T) { assert.NilError(t, err) assert.DeepEqual(t, expected, result) } + +func TestShoudLogJSON(t *testing.T) { + // Test with no env or args + result := utils.ShoudLogJSON([]string{"FOO=bar"}, []string{"tinyauth", "--foo-bar=baz"}) + assert.Equal(t, false, result) + + // Test with env variable set + result = utils.ShoudLogJSON([]string{"LOG_JSON=true"}, []string{"tinyauth", "--foo-bar=baz"}) + assert.Equal(t, true, result) + + // Test with flag set + result = utils.ShoudLogJSON([]string{"FOO=bar"}, []string{"tinyauth", "--log-json=true"}) + assert.Equal(t, true, result) + + // Test with both env and flag set to false + result = utils.ShoudLogJSON([]string{"LOG_JSON=false"}, []string{"tinyauth", "--log-json=false"}) + assert.Equal(t, false, result) +} diff --git a/main.go b/main.go index 3632749..893e62f 100644 --- a/main.go +++ b/main.go @@ -4,12 +4,16 @@ import ( "os" "time" "tinyauth/cmd" + "tinyauth/internal/utils" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) func main() { - log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}).With().Timestamp().Caller().Logger() + log.Logger = log.Logger.With().Timestamp().Caller().Logger() + if !utils.ShoudLogJSON(os.Environ(), os.Args) { + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}) + } cmd.Run() }