From e6b75e5348eb198ea95408856349ed11dc4f4649 Mon Sep 17 00:00:00 2001 From: Matthieu 'JP' DERASSE Date: Tue, 10 Jan 2023 22:36:42 +0000 Subject: [PATCH] feat(logger): Add an utils func to add common env variables to logger field --- log/utils.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 log/utils.go diff --git a/log/utils.go b/log/utils.go new file mode 100644 index 0000000..1acf6ed --- /dev/null +++ b/log/utils.go @@ -0,0 +1,27 @@ +package log + +import ( + "fmt" + "os" + + "github.com/sirupsen/logrus" +) + +// list of common environment variables +var commonEnvs = []string{"APP_NAME", "APP_VERSION"} + +// AddCommonFieldsFromEnv will analyze "common" environment variable and will add those +// as fields on a logrus.Entry. +func AddCommonFieldsFromEnv(l *logrus.Entry) (*logrus.Entry, error) { + if l == nil { + return nil, fmt.Errorf("missing logrus entry") + } + + for _, envKey := range commonEnvs { + if v := os.Getenv(envKey); v != "" { + l = logrus.WithField(envKey, v) + } + } + + return l, nil +}