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

enable passing custom logger #7

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

LukasJenicek
Copy link

@LukasJenicek LukasJenicek commented Jul 10, 2024

This way I can let ppl to modify the logging in any way..

We could have in our codebase slog.Logger like this:

type Slogger struct {
	log                  *slog.Logger
	printResponsePayload bool
}

func NewSlogger(log *slog.Logger, printResponsePayload bool) *Slogger {
	return &Slogger{
		log:                  log,
		printResponsePayload: printResponsePayload,
	}
}

func (s *Slogger) LogRequest(r *http.Request, curl *http2curl.CurlCommand) {
	s.log.Info(curl.String())
	s.log.Info(fmt.Sprintf("request: %s %s", r.Method, r.___URL))
}

func (s *Slogger) LogResponse(r *http.Request, resp *http.Response, startTime time.Time) {
	if resp == nil {
		s.log.Warn(fmt.Sprintf("response (<nil>): %v", r.___URL.String()), slog.Duration("duration", time.Since(startTime)))
		return
	}

	if resp.StatusCode >= 400 {
		s.log.Error(fmt.Sprintf("response: %s %s", resp.Status, resp.Request.___URL))
		return
	}

	s.log.Info(fmt.Sprintf("response: %s %s", resp.Status, resp.Request.___URL))

	if s.printResponsePayload && resp.Header.Get("Content-Type") == "application/json" {
		var b bytes.Buffer

		tee := io.TeeReader(resp.Body, &b)
		resp.Body = io.NopCloser(&b)

		payload, err := io.ReadAll(tee)
		if err == nil {
			// Pretty print the JSON payload
			var prettyJSON bytes.Buffer
			if err := json.Indent(&prettyJSON, payload, "", "    "); err == nil {
				s.log.Info(prettyJSON.String())
			}
		}
	}
}

@LukasJenicek LukasJenicek changed the title add possibility to modify logging of http request and reponse enable passing custom logger Jul 10, 2024
return RoundTripFunc(func(req *http.Request) (resp *http.Response, err error) {
r := CloneRequest(req)
type RequestLogger interface {
LogRequest(req *http.Request, curl *http2curl.CurlCommand)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not a fan of http2curl being part of any public interface

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense. Should I pass string directly ?

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

Successfully merging this pull request may close these issues.

2 participants