@@ -50,24 +50,31 @@ func Example_handler() {
50
50
51
51
// Install some provided extra handlers to set some request's context fields.
52
52
// Thanks to those handlers, all our logs will come with some pre-populated fields.
53
- c = c .Append (hlog .RemoteAddrHandler ( "ip " ))
53
+ c = c .Append (hlog .HTTPVersionHandler ( "http_version " ))
54
54
c = c .Append (hlog .UserAgentHandler ("user_agent" ))
55
- c = c .Append (hlog .RefererHandler ( "referer " ))
55
+ c = c .Append (hlog .URLHandler ( "url " ))
56
56
//c = c.Append(hlog.RequestIDHandler("req_id", "Request-Id"))
57
57
58
58
// Here is your final handler
59
59
h := c .Then (http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
60
+ status := http .StatusOK // Your business logic here
61
+
60
62
// Get the logger from the request's context. You can safely assume it
61
63
// will be always there: if the handler is removed, hlog.FromRequest
62
64
// will return a no-op logger.
63
65
hlog .FromRequest (r ).Info ().
64
66
Str ("user" , "current user" ).
65
- Str ("status" , "ok" ).
67
+ Int ("status" , status ).
66
68
Msg ("Something happened" )
67
69
}))
68
- http .Handle ("/" , h )
69
70
70
- h .ServeHTTP (httptest .NewRecorder (), & http.Request {})
71
+ ts := httptest .NewServer (h )
72
+ defer ts .Close ()
73
+
74
+ _ , err := http .Get (ts .URL )
75
+ if err != nil {
76
+ panic ("http.Get failed" )
77
+ }
71
78
72
- // Output: {"level":"info","role":"my-service","host":"local-hostname","user":"current user","status":"ok" ,"time":"2001-02-03T04:05:06Z","message":"Something happened"}
79
+ // Output: {"level":"info","role":"my-service","host":"local-hostname","http_version":"1.1","user_agent":"Go-http-client/1.1","url":"/"," user":"current user","status":200 ,"time":"2001-02-03T04:05:06Z","message":"Something happened"}
73
80
}
0 commit comments