Go combat--Implement a log of your own network request HttpLogger (The Go)

Source: Internet
Author: User

Life goes on and on Go Go go~~~

Before we briefly introduced the log package and the Net/http package in the go language, we'll do something today and combine the two to achieve our own logging network requests.

In addition, we haven't introduced you to the time package, but we can also read it.

First, I default you to understand the organizational structure of the go language.

Import the required package
We need a log net/http time three pack

package httploggerimport (    "log"    "net/http"    "time")

Implement a struct

type loggedRoundTripper struct {    rt  http.RoundTripper    log HTTPLogger}

where HTTP. Roudtripper:
Roundtripper is an interface representing the ability to execute a single HTTP transaction obtaining the Response for a G Iven Request.

Implement an interface HttpLogger

type HTTPLogger interface {    LogRequest(*http.Request)    LogResponse(*http.Request, *http.Response, error, time.Duration)}

Implementation functions:

Type Defaultlogger struct {}func (DL Defaultlogger) logrequest (*http. Request) {}func (DL Defaultlogger) Logresponse (req*http. Request, Res*http. Response, err error, duration Time. Duration) {Duration/= Time. MillisecondifErr! = Nil {Log. Printf ("HTTP Request method=%s host=%s path=%s status=error durationms=%d error= %q", req. Method, req. Host, req. Url. Path, duration, err. Error ())}Else{Log. Printf ("HTTP Request method=%s host=%s path=%s status=%d durationms=%d" , req. Method, req. Host, req. Url. Path, Res. StatusCode, Duration)}}

Full code

 PackageHttploggerimport ("Log"    "Net/http"    "Time") type Loggedroundtripper struct {rt http. RoundtripperLogHttplogger}func (c*loggedroundtripper) Roundtrip (Request*http. Request) (*http. Response, error) {C.Log. Logrequest (Request) StartTime: = Time. Now () response, Err: = C.rt.roundtrip (Request) Duration: = Time. Since (StartTime) c.Log. Logresponse (Request, Response, err, duration)returnResponse, err}//Newloggedtransport takes an HTTP. Roundtripper andReturns a new one that logs requests andResponsesfunc Newloggedtransport (Rt http. Roundtripper,LogHttpLogger) http. Roundtripper {return&loggedroundtripper{rt:rt,Log:Log}}//HttpLogger defines the interface toLogHTTP request andResponsestype HttpLogger Interface {logrequest (*http. Request) Logresponse (*http. Request,*http. Response, Error, Time. Duration)}//Defaultlogger is a HTTP logger that'll UseThe standard logger in theLog  PackageTo provide basic information about HTTP Responsestype defaultlogger struct {}//logrequest doens' t do anything since we 'll be logging replies Onlyfunc (DL Defaultlogger) logrequest (*http. Request) {}//logresponse logs path, host, status code andDuration in Millisecondsfunc (DL Defaultlogger) Logresponse (req*http. Request, Res*http. Response, err error, duration Time. Duration) {Duration/= Time. MillisecondifErr! = Nil {Log. Printf ("HTTP Request method=%s host=%s path=%s status=error durationms=%d error=  %q", req. Method, req. Host, req. Url. Path, duration, err. Error ())}Else{Log. Printf ("HTTP Request method=%s host=%s path=%s status=%d durationms=%d ", req. Method, req. Host, req. Url. Path, Res. StatusCode, duration)}}//Defaultloggedtransport wraps http. Defaulttransport toLogUsing Defaultloggervar defaultloggedtransport = Newloggedtransport (http. Defaulttransport, defaultlogger{})

Use
Implementing the interface:

Type HttpLogger struct {Log *log. Logger}func Newlogger ()*httplogger{return&httplogger{Log:Log. New (OS. Stderr,"Log-",Log. Lstdflags),}}func (l*httplogger) Logrequest (req*http. Request) {L.Log. Printf ("Request %s %s", req. Method, req. Url. String (),)}func (l*httplogger) Logresponse (req*http. Request, Res*http. Response, err error, duration Time. Duration) {Duration/= Time. MillisecondifErr! = Nil {L.Log. PRINTLN (ERR)}ElseL.Log. Printf ("Response method=%s status=%d durationms=%d %s", req. Method, Res. StatusCode, duration, req. Url. String (),)}}

Full code:

 PackageMainimport ("Log"    "Net/http"    "OS"    "Time"    "Httplogger/httplogger") Func Main () {client: = http. client{Transport:httplogger. Newloggedtransport (http. Defaulttransport, Newlogger ()),} client. Get ("Https://www.baidu.com")}type HttpLogger struct {Log *log. Logger}func Newlogger ()*httplogger{return&httplogger{Log:Log. New (OS. Stderr,"Log-",Log. Lstdflags),}}func (l*httplogger) Logrequest (req*http. Request) {L.Log. Printf ("Request %s %s", req. Method, req. Url. String (),)}func (l*httplogger) Logresponse (req*http. Request, Res*http. Response, err error, duration Time. Duration) {Duration/= Time. MillisecondifErr! = Nil {L.Log. PRINTLN (ERR)}ElseL.Log. Printf ("Response method=%s status=%d durationms=%d %s", req. Method, Res. StatusCode, duration, req. Url. String (),)}}

Results:
LOG-2017/04/18 23:39:41 Request GET https://www.baidu.com
LOG-2017/04/18 23:39:42 Response method=get status=200 durationms=614 https://www.baidu.com

Go combat--Implement a log of your own network request HttpLogger (The Go)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.