Configure logging level and format

This commit is contained in:
Dan Sosedoff 2022-12-06 12:09:21 -06:00
parent 3e1a93296e
commit dbd3b26f6c
No known key found for this signature in database
GPG Key ID: 26186197D282B164
3 changed files with 36 additions and 3 deletions

View File

@ -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 {

View File

@ -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)}

View File

@ -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")
}