Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question around log formatting #1581

Closed
eklein opened this issue Oct 2, 2018 · 4 comments
Closed

Question around log formatting #1581

eklein opened this issue Oct 2, 2018 · 4 comments

Comments

@eklein
Copy link

eklein commented Oct 2, 2018

I am looking at trying to add one or two additional fields to the standard LoggerWithWriter() output.

Example before:

[GIN] 2018/09/26 - 23:30:55 | 204 | 9.908935ms | 10.10.10.1 | DELETE /uri/path

Example of what I'd like to add after:

[GIN] 2018/09/26 - 23:30:55 | 204 | 9.908935ms | 10.52.161.250 | <username or payload information> | DELETE /uri/path

I haven't found a ton of resources in terms of folks overriding this default logger. I see quite a few instances where folks add some middleware to output extra data in addition to this standard logging, but I'd love to see if there's a way to augment the existing log line with additional data.

Thanks in advance for any assistance!

@yeqown
Copy link

yeqown commented Dec 5, 2018

@eklein Maybe it's a good way to maintain your own Logger middleware? I just have one like this:

type respBodyWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w respBodyWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}

// LogRequest is a middleware to log each request
func LogRequest(Logger *logger.Logger, logResponse bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		rbw := &respBodyWriter{
			body:           bytes.NewBufferString(""),
			ResponseWriter: c.Writer,
		}
		c.Writer = rbw

		start := time.Now()
		ctxCpy := c.Copy()

		c.Next()

		latency := time.Now().Sub(start)
		fields := make(map[string]interface{})
		fields["requestData"] = parseRequestForm(ctxCpy)
		if logResponse {
			fields["responseData"] = rbw.body.String()
		}

		Logger.WithFields(fields).Infof("[Request] %v |%3d| %13v | %15s |%-7s %s",
			start.Format("2006/01/02 - 15:04:05"),
			c.Writer.Status(),
			latency,
			c.ClientIP(),
			c.Request.Method,
			c.Request.URL.Path,
		)
	}
}

I hope this would be help and not too late ~

@thinkerou
Copy link
Member

#1677 merged!

@eklein
Copy link
Author

eklein commented Dec 12, 2018

🎉 Thank you for the heads-up @thinkerou! I found a way around it in the meantime, I'll circle back and check out what was just merged.

@thinkerou
Copy link
Member

@eklein thanks! please use it and feed back us if it have any problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants