Allow logger defaults to be configured through environment variables (#266)

These environment variables configure defaults for the logger related
flags:
* `BRICKS_LOG_FILE`
* `BRICKS_LOG_LEVEL`
* `BRICKS_LOG_FORMAT`
This commit is contained in:
Pieter Noordhuis 2023-03-21 17:05:04 +01:00 committed by GitHub
parent 7dcc0d4b41
commit 9100680162
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 19 additions and 0 deletions

View File

@ -3,6 +3,7 @@ package root
import ( import (
"context" "context"
"fmt" "fmt"
"os"
"github.com/databricks/bricks/libs/flags" "github.com/databricks/bricks/libs/flags"
"github.com/databricks/bricks/libs/log" "github.com/databricks/bricks/libs/log"
@ -10,6 +11,12 @@ import (
"golang.org/x/exp/slog" "golang.org/x/exp/slog"
) )
const (
envBricksLogFile = "BRICKS_LOG_FILE"
envBricksLogLevel = "BRICKS_LOG_LEVEL"
envBricksLogFormat = "BRICKS_LOG_FORMAT"
)
func initializeLogger(ctx context.Context, cmd *cobra.Command) (context.Context, error) { func initializeLogger(ctx context.Context, cmd *cobra.Command) (context.Context, error) {
opts := slog.HandlerOptions{} opts := slog.HandlerOptions{}
opts.Level = logLevel.Level() opts.Level = logLevel.Level()
@ -41,6 +48,18 @@ var logLevel = flags.NewLogLevelFlag()
var logOutput = flags.OutputText var logOutput = flags.OutputText
func init() { func init() {
// Configure defaults from environment, if applicable.
// If the provided value is invalid it is ignored.
if v, ok := os.LookupEnv(envBricksLogFile); ok {
logFile.Set(v)
}
if v, ok := os.LookupEnv(envBricksLogLevel); ok {
logLevel.Set(v)
}
if v, ok := os.LookupEnv(envBricksLogFormat); ok {
logOutput.Set(v)
}
RootCmd.PersistentFlags().Var(&logFile, "log-file", "file to write logs to") RootCmd.PersistentFlags().Var(&logFile, "log-file", "file to write logs to")
RootCmd.PersistentFlags().Var(&logLevel, "log-level", "log level") RootCmd.PersistentFlags().Var(&logLevel, "log-level", "log level")
RootCmd.PersistentFlags().Var(&logOutput, "log-format", "log output format (text or json)") RootCmd.PersistentFlags().Var(&logOutput, "log-format", "log output format (text or json)")