()
| 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 | } |
nothing calls this directly
no test coverage detected