Logging in go-api-basic

A bearded gopher with a lightsaber cutting up some logs

Thoughts on Logging

Logging in go-api-basic with zerolog

Setting Logger State on Startup

// setup logger with appropriate defaults
lgr := logger.NewLogger(os.Stdout, minlvl, true)
// initialize server configuration parameters
params := app.NewServerParams(lgr, serverDriver)
// initialize Server
s, err := app.NewServer(mr, params)
if err != nil {
lgr.Fatal().Err(err).Msg(“Error from app.NewServer”)
}

Logger Setup in Handlers

// register routes/middleware/handlers to the Server router
func (s *Server) routes() {
// Match only POST requests at /api/v1/movies
// with Content-Type header = application/json
s.router.Handle(moviesV1PathRoot,
s.loggerChain().Extend(s.ctxWithUserChain()).
Append(s.authorizeUserHandler).
Append(s.jsonContentTypeResponseHandler).
ThenFunc(s.handleMovieCreate)).
Methods(http.MethodPost).
Headers(contentTypeHeaderKey, appJSONContentTypeHeaderVal)
...
The above error log demonstrates a log for an error with stack trace turned off.

Reading and Modifying Logger State

curl --location --request GET 'http://127.0.0.1:8080/api/v1/logger' \ --header 'Authorization: Bearer <REPLACE WITH ACCESS TOKEN>'
curl --location --request PUT 'http://127.0.0.1:8080/api/v1/logger' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <REPLACE WITH ACCESS TOKEN>' \ --data-raw '{ "global_log_level": "debug", "log_error_stack": "true" }'

Go enthusiast; Loyalty/CRM Technology Leader; Drummer; Vinyl geek; Husband/Dad