hlog

package
v0.0.0-...-349f3ea Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2023 License: MIT Imports: 16 Imported by: 0

README

hlog

log http client and service detail

usage

online demo

package main

import (
	"net/http"
	"time"

	"github.com/bingoohuang/golog"
	"github.com/bingoohuang/golog/pkg/hlog"
	"github.com/bingoohuang/sariaf"
	"github.com/sirupsen/logrus"
)

func main() {
	golog.Setup()
	r := sariaf.New()
	r.GET("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello World")) })
	r.GET("/posts", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("GET: Get All Posts")) })
	server := &http.Server{Addr: ":8080", Handler: hlog.LogWrapHandler(r, logrus.StandardLogger())}

	go server.ListenAndServe()

	time.Sleep(100 * time.Millisecond)

	client := hlog.NewLoggedHTTPClient(logrus.StandardLogger())
	client.Get("http://127.0.0.1:8080")
	client.Post("http://127.0.0.1:8080/posts", "", nil)
}
2020-12-22 10:34:55.726 [INFO ] 62201 --- [19   ] [-] hlog.DefaultLogger.LogRequest hlog.go:75 : Client Request GET / HTTP/1.1\r\nHost: 127.0.0.1:64755
2020-12-22 10:34:55.727 [INFO ] 62201 --- [5    ] [-] hlog.DefaultLogger.LogRequest hlog.go:75 : Server Request GET / HTTP/1.1\r\nHost: 127.0.0.1:64755\r\nAccept-Encoding: gzip\r\nUser-Agent: Go-http-client/1.1
2020-12-22 10:34:55.727 [INFO ] 62201 --- [5    ] [-] hlog.DefaultLogger.LogWriter server.go:108 : Server Response duration:8.55µs status:0 header:map[] payload:Hello World
2020-12-22 10:34:55.728 [INFO ] 62201 --- [19   ] [-] hlog.DefaultLogger.LogResponse hlog.go:92 : Client Response Duration:975.296µs error:<nil> Dump:HTTP/1.1 200 OK\r\nContent-Length: 11\r\nContent-Type: text/plain; charset=utf-8\r\nDate: Tue, 22 Dec 2020 02:34:55 GMT\r\n\r\nHello World
2020-12-22 10:34:55.728 [INFO ] 62201 --- [19   ] [-] hlog.DefaultLogger.LogRequest hlog.go:75 : Client Request POST /posts HTTP/1.1\r\nHost: 127.0.0.1:64755
2020-12-22 10:34:55.728 [INFO ] 62201 --- [5    ] [-] hlog.DefaultLogger.LogRequest hlog.go:75 : Server Request POST /posts HTTP/1.1\r\nHost: 127.0.0.1:64755\r\nAccept-Encoding: gzip\r\nContent-Length: 0\r\nUser-Agent: Go-http-client/1.1
2020-12-22 10:34:55.728 [INFO ] 62201 --- [5    ] [-] hlog.DefaultLogger.LogWriter server.go:108 : Server Response duration:8.856µs status:404 header:map[Content-Type:[text/plain; charset=utf-8] X-Content-Type-Options:[nosniff]] payload:Not Found
2020-12-22 10:34:55.729 [INFO ] 62201 --- [19   ] [-] hlog.DefaultLogger.LogResponse hlog.go:92 : Client Response Duration:475.722µs error:<nil> Dump:HTTP/1.1 404 Not Found\r\nContent-Length: 10\r\nContent-Type: text/plain; charset=utf-8\r\nDate: Tue, 22 Dec 2020 02:34:55 GMT\r\nX-Content-Type-Options: nosniff\r\n\r\nNot Found

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultStdLogTransport wraps http.DefaultTransport to log using std log.
	DefaultStdLogTransport = NewTransport(http.DefaultTransport, HLog{Printfer: StdLogger{}})

	// DefaultLoggusTransport wraps http.DefaultTransport to log using logrus.
	DefaultLoggusTransport = NewTransport(http.DefaultTransport, HLog{Printfer: logrus.StandardLogger()})
)

Functions

func Abbreviate

func Abbreviate(s string, n int) (string, string)

func AbbreviateBytes

func AbbreviateBytes(s []byte, n int) (string, string)

func AbbreviateBytesEnv

func AbbreviateBytesEnv(contentType string, s []byte) (string, string)

func AbbreviateEnv

func AbbreviateEnv(contentType, s string) (string, string)

func EnvSize

func EnvSize(envName string, defaultValue int) int

func NewHTTPClient

func NewHTTPClient(logger Printfer) *http.Client

NewHTTPClient creates a new *http.Client with logging.

func NewStdLogHTTPClient

func NewStdLogHTTPClient() *http.Client

NewStdLogHTTPClient creates a new *http.Client with log.

func NewTransport

func NewTransport(rt http.RoundTripper, log interface{}) http.RoundTripper

NewTransport takes a http.RoundTripper and returns a new one that logs requests and responses

func StdLogWrapHandler

func StdLogWrapHandler(h http.Handler) http.Handler

StdLogWrapHandler wraps a http.Handler for logging.

func Unwrap

Unwrap returns the underlying http.ResponseWriter from within zero or more layers of httpsnoop wrappers.

func Wrap

Wrap returns a wrapped version of w that provides the exact same interface as w. Specifically if w implements any combination of:

- http.Flusher - http.CloseNotifier - http.Hijacker - io.ReaderFrom - http.Pusher

The wrapped version will implement the exact same combination. If no hooks are set, the wrapped version also behaves exactly as w. Hooks targeting methods not supported by w are ignored. Any other hooks will intercept the method they target and may modify the call's arguments and/or return values. The CaptureMetrics implementation serves as a working example for how the hooks can be used.

func WrapHandler

func WrapHandler(h http.Handler, logger Printfer) http.Handler

WrapHandler wraps a http.Handler for logging.

Types

type CloseNotifyFunc

type CloseNotifyFunc func() <-chan bool

CloseNotifyFunc is part of the http.CloseNotifier interface.

type FlushFunc

type FlushFunc func()

FlushFunc is part of the http.Flusher interface.

type HLog

type HLog struct {
	Printfer
	RequestID string
}

HLog is a http logger that will use the standard logger in the log package to provide basic information about http responses.

func (*HLog) LogRecover

func (dl *HLog) LogRecover(side string, duration time.Duration, recover interface{}, debugStack []byte)

LogRecover logs the recover information.

func (*HLog) LogRequest

func (dl *HLog) LogRequest(side string, r *http.Request)

LogRequest logs the request.

func (*HLog) LogResponse

func (dl *HLog) LogResponse(side string, req *http.Request, res *http.Response, err error, duration time.Duration)

LogResponse logs path, host, status code and duration in milliseconds.

func (*HLog) LogWriter

func (dl *HLog) LogWriter(duration time.Duration, status int, header http.Header, payload string)

LogWriter logs the writer information.

type HTTPRequestLogger

type HTTPRequestLogger interface {
	LogRequest(side string, req *http.Request)
}

HTTPRequestLogger defines the interface to log http request.

type HTTPResponseLogger

type HTTPResponseLogger interface {
	LogResponse(side string, req *http.Request, rsp *http.Response, err error, duration time.Duration)
}

HTTPResponseLogger defines the interface to log http response.

type HTTPWriterLogger

type HTTPWriterLogger interface {
	LogWriter(duration time.Duration, status int, header http.Header, payload string)
}

HTTPWriterLogger logs the server writer.

type HeaderFunc

type HeaderFunc func() http.Header

HeaderFunc is part of the http.ResponseWriter interface.

type HijackFunc

type HijackFunc func() (net.Conn, *bufio.ReadWriter, error)

HijackFunc is part of the http.Hijacker interface.

type Hooks

type Hooks struct {
	Header      func(HeaderFunc) HeaderFunc
	WriteHeader func(WriteHeaderFunc) WriteHeaderFunc
	Write       func(WriteFunc) WriteFunc
	Flush       func(FlushFunc) FlushFunc
	CloseNotify func(CloseNotifyFunc) CloseNotifyFunc
	Hijack      func(HijackFunc) HijackFunc
	ReadFrom    func(ReadFromFunc) ReadFromFunc
	Push        func(PushFunc) PushFunc
}

Hooks defines a set of method interceptors for methods included in http.ResponseWriter as well as some others. You can think of them as middleware for the function calls they target. See Wrap for more details.

type LogWrapper

type LogWrapper struct {
	Log interface{}
}

LogWrapper is a log wrap to wrap http service.

func NewLogWrapper

func NewLogWrapper(logger Printfer) *LogWrapper

NewLogWrapper creates a new *LogWrapper.

func NewStdLogWrapper

func NewStdLogWrapper() *LogWrapper

NewStdLogWrapper creates a new *LogWrapper.

func (LogWrapper) LogWrap

func (dl LogWrapper) LogWrap(h http.HandlerFunc) http.HandlerFunc

LogWrap wraps a HandlerFunc with logging around.

func (LogWrapper) LogWrapHandler

func (dl LogWrapper) LogWrapHandler(h http.Handler) http.Handler

LogWrapHandler wraps a http.Handler for logging.

func (LogWrapper) ServeHTTP

func (dl LogWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request, h http.HandlerFunc)

type Metrics

type Metrics struct {
	Header http.Header

	// Code is the first http response code passed to the WriteHeader func of
	// the ResponseWriter. If no such call is made, a default code of 200 is
	// assumed instead.
	Code int
	// Duration is the time it took to execute the handler.
	Duration time.Duration
	// Written is the number of bytes successfully written by the Write or
	// ReadFrom function of the ResponseWriter. ResponseWriters may also write
	// data to their underlaying connection directly (e.g. headers), but those
	// are not tracked. Therefor the number of Written bytes will usually match
	// the size of the response body.
	Written int64
	// contains filtered or unexported fields
}

Metrics holds metrics captured from CaptureMetrics.

func CaptureMetrics

func CaptureMetrics(hnd http.Handler, w http.ResponseWriter, r *http.Request) Metrics

CaptureMetrics wraps the given hnd, executes it with the given w and r, and returns the metrics it captured from it.

func CaptureMetricsFn

func CaptureMetricsFn(w http.ResponseWriter, fn func(http.ResponseWriter)) Metrics

CaptureMetricsFn wraps w and calls fn with the wrapped w and returns the resulting metrics. This is very similar to CaptureMetrics (which is just sugar on top of this func), but is a more usable interface if your application doesn't use the Go http.Handler interface.

func (*Metrics) CaptureMetrics

func (m *Metrics) CaptureMetrics(w http.ResponseWriter, fn func(http.ResponseWriter))

CaptureMetrics wraps w and calls fn with the wrapped w and updates Metrics m with the resulting metrics. This is similar to CaptureMetricsFn, but allows one to customize starting Metrics object.

type Printfer

type Printfer interface {
	Printf(format string, v ...interface{})
}

Printfer is the interface to print log.

type PushFunc

type PushFunc func(target string, opts *http.PushOptions) error

PushFunc is part of the http.Pusher interface.

type ReadFromFunc

type ReadFromFunc func(src io.Reader) (int64, error)

ReadFromFunc is part of the io.ReaderFrom interface.

type RecoverLogger

type RecoverLogger interface {
	LogRecover(side string, duration time.Duration, recover interface{}, debugStack []byte)
}

RecoverLogger logs the recover info.

type RoundTripper

type RoundTripper struct {
	http.RoundTripper
	Log interface{}
}

func (*RoundTripper) RoundTrip

func (c *RoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip ...

type StdLogger

type StdLogger struct{}

func (StdLogger) Printf

func (h StdLogger) Printf(format string, v ...interface{})

type Unwrapper

type Unwrapper interface {
	Unwrap() http.ResponseWriter
}

type WriteFunc

type WriteFunc func(b []byte) (int, error)

WriteFunc is part of the http.ResponseWriter interface.

type WriteHeaderFunc

type WriteHeaderFunc func(code int)

WriteHeaderFunc is part of the http.ResponseWriter interface.

Jump to

Keyboard shortcuts

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