Merge pull request #605 from sosedoff/log-level

Configure logging level and format
This commit is contained in:
Dan Sosedoff 2022-12-06 12:41:56 -06:00 committed by GitHub
commit f4b3091666
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 41 additions and 17 deletions

View File

@ -55,6 +55,7 @@ func RequestLogger(logger *logrus.Logger) gin.HandlerFunc {
"method": c.Request.Method, "method": c.Request.Method,
"remote_addr": c.ClientIP(), "remote_addr": c.ClientIP(),
"duration": latency, "duration": latency,
"path": path,
} }
if err := c.Errors.Last(); err != nil { if err := c.Errors.Last(); err != nil {
@ -64,10 +65,14 @@ func RequestLogger(logger *logrus.Logger) gin.HandlerFunc {
// Additional fields for debugging // Additional fields for debugging
if debug { if debug {
fields["raw_query"] = c.Request.URL.RawQuery fields["raw_query"] = c.Request.URL.RawQuery
if c.Request.Method != http.MethodGet {
fields["raw_form"] = c.Request.Form
}
} }
entry := logrus.WithFields(fields) entry := logger.WithFields(fields)
msg := "http_request " + path msg := "http_request"
switch { switch {
case status >= http.StatusBadRequest && status < http.StatusInternalServerError: case status >= http.StatusBadRequest && status < http.StatusInternalServerError:

View File

@ -1,7 +1,6 @@
package api package api
import ( import (
"log"
"strings" "strings"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@ -49,14 +48,6 @@ func dbCheckMiddleware() gin.HandlerFunc {
} }
} }
// Middleware to print out request parameters and body for debugging
func requestInspectMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
err := c.Request.ParseForm()
log.Println("Request params:", err, c.Request.Form)
}
}
// Middleware to inject CORS headers // Middleware to inject CORS headers
func corsMiddleware() gin.HandlerFunc { func corsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {

View File

@ -7,10 +7,6 @@ import (
) )
func SetupMiddlewares(group *gin.RouterGroup) { func SetupMiddlewares(group *gin.RouterGroup) {
if command.Opts.Debug {
group.Use(requestInspectMiddleware())
}
if command.Opts.Cors { if command.Opts.Cors {
group.Use(corsMiddleware()) group.Use(corsMiddleware())
} }

View File

@ -158,8 +158,9 @@ func initOptions() {
os.Exit(0) os.Exit(0)
} }
if options.Debug { if err := configureLogger(opts); err != nil {
logger.SetLevel(logrus.DebugLevel) exitWithMessage(err.Error())
return
} }
if options.ReadOnly { if options.ReadOnly {
@ -175,6 +176,29 @@ func initOptions() {
printVersion() 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() { func printVersion() {
fmt.Println(command.VersionString()) fmt.Println(command.VersionString())
} }

View File

@ -8,6 +8,7 @@ import (
"strings" "strings"
"github.com/jessevdk/go-flags" "github.com/jessevdk/go-flags"
"github.com/sirupsen/logrus"
) )
const ( const (
@ -18,6 +19,8 @@ const (
type Options struct { type Options struct {
Version bool `short:"v" long:"version" description:"Print version"` Version bool `short:"v" long:"version" description:"Print version"`
Debug bool `short:"d" long:"debug" description:"Enable debugging mode"` 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"` URL string `long:"url" description:"Database connection string"`
Host string `long:"host" description:"Server hostname or IP" default:"localhost"` Host string `long:"host" description:"Server hostname or IP" default:"localhost"`
Port int `long:"port" description:"Server port" default:"5432"` Port int `long:"port" description:"Server port" default:"5432"`
@ -62,6 +65,11 @@ func ParseOptions(args []string) (Options, error) {
return opts, err return opts, err
} }
_, err = logrus.ParseLevel(opts.LogLevel)
if err != nil {
return opts, err
}
if opts.URL == "" { if opts.URL == "" {
opts.URL = getPrefixedEnvVar("DATABASE_URL") opts.URL = getPrefixedEnvVar("DATABASE_URL")
} }