diff --git a/_example/main.go b/_example/main.go index b9f150f..d517f88 100644 --- a/_example/main.go +++ b/_example/main.go @@ -1,6 +1,7 @@ package main import ( + "errors" "fmt" "math/rand" "net/http" @@ -109,6 +110,18 @@ func main() { c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix())) }) + // Example of a custom message to the log + r.GET("/message", logger.SetLogger( + logger.WithLogger(func(_ *gin.Context, l zerolog.Logger) zerolog.Logger { + return l.Output(gin.DefaultWriter).With().Logger() + }), + logger.WithMessage("Request ended"), + ), func(c *gin.Context) { + c.Error(errors.New("some error has occured here")) + c.Error(errors.New("and some error has occured there")) + c.String(http.StatusBadGateway, "pong "+fmt.Sprint(time.Now().Unix())) + }) + // Example of skipper usage r.GET("/health", logger.SetLogger( logger.WithSkipper(func(c *gin.Context) bool { diff --git a/logger.go b/logger.go index f835794..709f185 100644 --- a/logger.go +++ b/logger.go @@ -47,6 +47,8 @@ type config struct { serverErrorLevel zerolog.Level // pathLevels is a map of specific paths to log levels for requests with status code < 400. pathLevels map[string]zerolog.Level + // message is a custom string that sets a log-message when http-request has finished + message string } const loggerKey = "_gin-contrib/logger_" @@ -85,6 +87,7 @@ func SetLogger(opts ...Option) gin.HandlerFunc { clientErrorLevel: zerolog.WarnLevel, serverErrorLevel: zerolog.ErrorLevel, output: os.Stderr, + message: "Request", } // Apply each option to the config @@ -151,9 +154,8 @@ func SetLogger(opts ...Option) gin.HandlerFunc { } latency := end.Sub(start) - msg := "Request" if len(c.Errors) > 0 { - msg = c.Errors.String() + cfg.message += " with errors: " + c.Errors.String() } var evt *zerolog.Event @@ -182,7 +184,7 @@ func SetLogger(opts ...Option) gin.HandlerFunc { Dur("latency", latency). Str("user_agent", c.Request.UserAgent()). Int("body_size", c.Writer.Size()). - Msg(msg) + Msg(cfg.message) } } } diff --git a/options.go b/options.go index 2c5f3dd..3dbc343 100644 --- a/options.go +++ b/options.go @@ -157,3 +157,11 @@ func WithContext(fn func(*gin.Context, *zerolog.Event) *zerolog.Event) Option { c.context = fn }) } + +// WithMessage is an option to set a custom log-message, when http-request has finished and logged +// It takes a string as an argument and returns an Option. +func WithMessage(message string) Option { + return optionFunc(func(c *config) { + c.message = message + }) +}