...

Source file src/github.com/rs/zerolog/hlog/hlog_example_test.go

Documentation: github.com/rs/zerolog/hlog

     1  // +build !binary_log
     2  
     3  package hlog_test
     4  
     5  import (
     6  	"net/http"
     7  	"os"
     8  	"time"
     9  
    10  	"net/http/httptest"
    11  
    12  	"github.com/rs/zerolog"
    13  	"github.com/rs/zerolog/hlog"
    14  )
    15  
    16  // fake alice to avoid dep
    17  type middleware func(http.Handler) http.Handler
    18  type alice struct {
    19  	m []middleware
    20  }
    21  
    22  func (a alice) Append(m middleware) alice {
    23  	a.m = append(a.m, m)
    24  	return a
    25  }
    26  func (a alice) Then(h http.Handler) http.Handler {
    27  	for i := range a.m {
    28  		h = a.m[len(a.m)-1-i](h)
    29  	}
    30  	return h
    31  }
    32  
    33  func init() {
    34  	zerolog.TimestampFunc = func() time.Time {
    35  		return time.Date(2001, time.February, 3, 4, 5, 6, 7, time.UTC)
    36  	}
    37  }
    38  
    39  func Example_handler() {
    40  	log := zerolog.New(os.Stdout).With().
    41  		Timestamp().
    42  		Str("role", "my-service").
    43  		Str("host", "local-hostname").
    44  		Logger()
    45  
    46  	c := alice{}
    47  
    48  	// Install the logger handler with default output on the console
    49  	c = c.Append(hlog.NewHandler(log))
    50  
    51  	// Install some provided extra handlers to set some request's context fields.
    52  	// Thanks to those handlers, all our logs will come with some pre-populated fields.
    53  	c = c.Append(hlog.RemoteAddrHandler("ip"))
    54  	c = c.Append(hlog.UserAgentHandler("user_agent"))
    55  	c = c.Append(hlog.RefererHandler("referer"))
    56  	//c = c.Append(hlog.RequestIDHandler("req_id", "Request-Id"))
    57  
    58  	// Here is your final handler
    59  	h := c.Then(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    60  		// Get the logger from the request's context. You can safely assume it
    61  		// will be always there: if the handler is removed, hlog.FromRequest
    62  		// will return a no-op logger.
    63  		hlog.FromRequest(r).Info().
    64  			Str("user", "current user").
    65  			Str("status", "ok").
    66  			Msg("Something happened")
    67  	}))
    68  	http.Handle("/", h)
    69  
    70  	h.ServeHTTP(httptest.NewRecorder(), &http.Request{})
    71  
    72  	// Output: {"level":"info","role":"my-service","host":"local-hostname","user":"current user","status":"ok","time":"2001-02-03T04:05:06Z","message":"Something happened"}
    73  }
    74  

View as plain text