labstack/echo

Make request logger more user-friendly

noritama73 opened this issue · 4 comments

Issue Description

relate #2188

As you recommended, there is request logger to make customizable format. However, it doesn't seem to be very user-friendly. I have 2 ideas:

  1. Explicitly mention request logger in the document

Currently, there is no mention of request logger in the document. I suggest that we describe the usage, especially you're thinking that request logger is going mainstream.

  1. Add logger config like normal logger

I suggest that we config logger format by setting JSON tags, like this:

// equivalent to DefaultLoggerConfig
type DefaultRequestLoggerFormat struct {
	RemoteIP string `json:"remote_ip"`
	...
}

func (m RequestLoggerValues) ToDefaultRequestLoggerFormat() DefaultRequestLoggerFormat {
	// refill property
}

In application users make:

type CustomRequestLoggerFormat struct {
	DefaultRequestLoggerFormat {
	        CustomID string `json:"custom_id"`
        }
}

func writeRequestLog(c echo.Context, v middleware.RequestLoggerValues) error {
	custom := CustomRequestLoggerFormat{
		DefaultRequestLoggerFormat: v.ToDefaultRequestLoggerFormat(),
		CustomID: c.Get("USER_ID").(string),
	}
	msg, err := json.Marshal(custom)
	_, err = c.Logger().Output().Write(msg)
	return nil
}
aldas commented

Add logger config like normal logger

Request logger purpose is not to be configured from string. It is meant to be implemented by developer. Preferably not using Echo own logger but instead some of the popular structured logging libraries.

aldas commented

I think DefaultRequestLoggerFormat etc is quite redundant as you can get everything with something like that

  1. create custom struct with fields and json tags
  2. fill it inside LogValuesFunc with values from middleware.RequestLoggerValues object
  3. marshal to json
	e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
		LogRemoteIP: true,
		LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error {
			userID, _ := c.Get("USER_ID").(string)

			custom := struct {
				RemoteIP string `json:"remote_ip"`
				UserID   string `json:"user_id"`
			}{
				RemoteIP: v.RemoteIP,
				UserID:   userID,
			}
			msg, err := json.Marshal(custom)
			if err != nil {
				_, err = c.Logger().Output().Write(msg)
			}
			return err
		},
	}))

Sure, then I suggest that update the document. Please see labstack/echox#246

aldas commented

closing. docs are updated.

I suggest people to move to middleware.RequestLogger as it allows better integration 3rd party logging libraries and is more flexible for customization.