Skip to content

Option to set io.Writer on middleware initialization #128

@mingalevme

Description

@mingalevme

Problem:

In case of JSON logging you must set writer every request (cause WithLogger-fn is executed every request):

// Example of JSON format log
r.GET("/json", logger.SetLogger(
  logger.WithLogger(func(_ *gin.Context, l zerolog.Logger) zerolog.Logger {
    return l.Output(gin.DefaultWriter).With().Logger()
  }),
), func(c *gin.Context) {
  c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
})

So the command return l.Output(gin.DefaultWriter).With().Logger() is also executed every request.

Logger.Output() method deep clones Logger with entire context:

// github.com/rs/zerolog@v1.34.0/log.go
// Output duplicates the current logger and sets w as its output.
func (l Logger) Output(w io.Writer) Logger {
	l2 := New(w)
	l2.level = l.level
	l2.sampler = l.sampler
	l2.stack = l.stack
	if len(l.hooks) > 0 {
		l2.hooks = append(l2.hooks, l.hooks...)
	}
	if l.context != nil {
		l2.context = make([]byte, len(l.context), cap(l.context))
		copy(l2.context, l.context)
	}
	return l2
}

So in case of JSON logging runtime deep clones logger with the entire context every request. I'm sure it's not a desired behaviour for the majority of the developes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions