MCPcopy
hub / github.com/rs/zerolog / Example_handler

Function Example_handler

hlog/hlog_example_test.go:39–73  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

37}
38
39func 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}

Callers

nothing calls this directly

Calls 15

AppendMethod · 0.95
ThenMethod · 0.95
NewFunction · 0.92
NewHandlerFunction · 0.92
RemoteAddrHandlerFunction · 0.92
UserAgentHandlerFunction · 0.92
RefererHandlerFunction · 0.92
FromRequestFunction · 0.92
LoggerMethod · 0.80
WithMethod · 0.80
MsgMethod · 0.80
HandleMethod · 0.80

Tested by

no test coverage detected