Skip to content

Commit

Permalink
Merge pull request #930 from neo773/json-log
Browse files Browse the repository at this point in the history
feat: add JSON logging
  • Loading branch information
tolgaOzen authored Dec 10, 2023
2 parents dc96744 + 61e4273 commit 5bf831e
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
3 changes: 2 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ type (

// Log contains configuration for logging.
Log struct {
Level string `mapstructure:"level"` // Logging level
Level string `mapstructure:"level"` // Logging level
Output string `mapstructure:"output"` // Logging output format, e.g., text, json
}

// Tracer contains configuration for distributed tracing.
Expand Down
8 changes: 8 additions & 0 deletions pkg/cmd/flags/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,14 @@ func RegisterServeFlags(cmd *cobra.Command) {
panic(err)
}

flags.String("log-output", conf.Log.Output, "logger output valid values json, text")
if err = viper.BindPFlag("logger.output", flags.Lookup("log-output")); err != nil {
panic(err)
}
if err = viper.BindEnv("logger.output", "PERMIFY_LOG_OUTPUT"); err != nil {
panic(err)
}

// AUTHN
flags.Bool("authn-enabled", conf.Authn.Enabled, "enable server authentication")
if err = viper.BindPFlag("authn.enabled", flags.Lookup("authn-enabled")); err != nil {
Expand Down
18 changes: 15 additions & 3 deletions pkg/cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,21 @@ func serve() func(cmd *cobra.Command, args []string) error {
red := color.New(color.FgGreen)
_, _ = red.Printf(internal.Banner, internal.Version)

logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: getLogLevel(cfg.Log.Level),
}))
var handler slog.Handler
switch cfg.Log.Output {
case "json":
handler = slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: getLogLevel(cfg.Log.Level),
})
case "text":
handler = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: getLogLevel(cfg.Log.Level),
})
default:
return fmt.Errorf("invalid log output: %s", cfg.Log.Output)
}

logger := slog.New(handler)

slog.SetDefault(logger)

Expand Down

0 comments on commit 5bf831e

Please sign in to comment.