loghttp

package module
v0.0.0-...-29ae44b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2023 License: MIT Imports: 5 Imported by: 50

README

go-loghttp

Log http.Client's requests and responses automatically.

PkgGoDev

Synopsis

To log all the HTTP requests/responses, import github.com/motemen/go-loghttp/global.

package main

import (
	"io"
	"log"
	"net/http"
	"os"

	_ "github.com/motemen/go-loghttp/global" // Just this line!
)

func main() {
	resp, err := http.Get(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}

	io.Copy(os.Stdout, resp.Body)
}
% go run main.go http://example.com/
2014/12/02 13:36:27 ---> GET http://example.com/
2014/12/02 13:36:27 <--- 200 http://example.com/
<!doctype html>
...

Or set loghttp.Transport to http.Client's Transport field.

import "github.com/motemen/go-loghttp"

client := &http.Client{
	Transport: &loghttp.Transport{},
}

You can modify loghttp.Transport's LogRequest and LogResponse to customize logging function.

Author

motemen motemen@gmail.com

Documentation

Overview

Package loghttp provides automatic logging functionalities to http.Client.

Index

Constants

This section is empty.

Variables

View Source
var ContextKeyRequestStart = &contextKey{"RequestStart"}
View Source
var DefaultLogRequest = func(req *http.Request) {
	log.Printf("--> %s %s", req.Method, req.URL)
}

Used if transport.LogRequest is not set.

View Source
var DefaultLogResponse = func(resp *http.Response) {
	ctx := resp.Request.Context()
	if start, ok := ctx.Value(ContextKeyRequestStart).(time.Time); ok {
		log.Printf("<-- %d %s (%s)", resp.StatusCode, resp.Request.URL, roundtime.Duration(time.Now().Sub(start), 2))
	} else {
		log.Printf("<-- %d %s", resp.StatusCode, resp.Request.URL)
	}
}

Used if transport.LogResponse is not set.

View Source
var DefaultTransport = &Transport{
	Transport: http.DefaultTransport,
}

THe default logging transport that wraps http.DefaultTransport.

Functions

This section is empty.

Types

type Transport

type Transport struct {
	Transport   http.RoundTripper
	LogRequest  func(req *http.Request)
	LogResponse func(resp *http.Response)
}

Transport implements http.RoundTripper. When set as Transport of http.Client, it executes HTTP requests with logging. No field is mandatory.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip is the core part of this module and implements http.RoundTripper. Executes HTTP request with request/response logging.

Directories

Path Synopsis
Package global automatically sets http.DefaultTransport to loghttp.DefaultTransport when loaded.
Package global automatically sets http.DefaultTransport to loghttp.DefaultTransport when loaded.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL