From dbd3b26f6c9455ee484aabcb366a54a38b88415a Mon Sep 17 00:00:00 2001 From: Dan Sosedoff Date: Tue, 6 Dec 2022 12:09:21 -0600 Subject: [PATCH] Configure logging level and format --- pkg/api/logger.go | 3 ++- pkg/cli/cli.go | 28 ++++++++++++++++++++++++++-- pkg/command/options.go | 8 ++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/pkg/api/logger.go b/pkg/api/logger.go index 2f0b15c..7d5fea8 100644 --- a/pkg/api/logger.go +++ b/pkg/api/logger.go @@ -55,6 +55,7 @@ func RequestLogger(logger *logrus.Logger) gin.HandlerFunc { "method": c.Request.Method, "remote_addr": c.ClientIP(), "duration": latency, + "path": path, } if err := c.Errors.Last(); err != nil { @@ -66,7 +67,7 @@ func RequestLogger(logger *logrus.Logger) gin.HandlerFunc { fields["raw_query"] = c.Request.URL.RawQuery } - entry := logrus.WithFields(fields) + entry := logger.WithFields(fields) msg := "http_request " + path switch { diff --git a/pkg/cli/cli.go b/pkg/cli/cli.go index bb3e306..b36778c 100644 --- a/pkg/cli/cli.go +++ b/pkg/cli/cli.go @@ -158,8 +158,9 @@ func initOptions() { os.Exit(0) } - if options.Debug { - logger.SetLevel(logrus.DebugLevel) + if err := configureLogger(opts); err != nil { + exitWithMessage(err.Error()) + return } if options.ReadOnly { @@ -175,6 +176,29 @@ func initOptions() { printVersion() } +func configureLogger(opts command.Options) error { + if options.Debug { + logger.SetLevel(logrus.DebugLevel) + } else { + lvl, err := logrus.ParseLevel(opts.LogLevel) + if err != nil { + return err + } + logger.SetLevel(lvl) + } + + switch options.LogFormat { + case "text": + logger.SetFormatter(&logrus.TextFormatter{}) + case "json": + logger.SetFormatter(&logrus.JSONFormatter{}) + default: + return fmt.Errorf("invalid logger format: %v", options.LogFormat) + } + + return nil +} + func printVersion() { chunks := []string{fmt.Sprintf("Pgweb v%s", command.Version)} diff --git a/pkg/command/options.go b/pkg/command/options.go index 643d2aa..05f19d6 100644 --- a/pkg/command/options.go +++ b/pkg/command/options.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/jessevdk/go-flags" + "github.com/sirupsen/logrus" ) const ( @@ -18,6 +19,8 @@ const ( type Options struct { Version bool `short:"v" long:"version" description:"Print version"` Debug bool `short:"d" long:"debug" description:"Enable debugging mode"` + LogLevel string `long:"log-level" description:"Logging level" default:"info"` + LogFormat string `long:"log-format" description:"Logging output format" default:"text"` URL string `long:"url" description:"Database connection string"` Host string `long:"host" description:"Server hostname or IP" default:"localhost"` Port int `long:"port" description:"Server port" default:"5432"` @@ -62,6 +65,11 @@ func ParseOptions(args []string) (Options, error) { return opts, err } + _, err = logrus.ParseLevel(opts.LogLevel) + if err != nil { + return opts, err + } + if opts.URL == "" { opts.URL = getPrefixedEnvVar("DATABASE_URL") }