Dan Gillis

Jul 13, 2021

6 min read

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

  • panic (zerolog.PanicLevel, 5)
  • fatal (zerolog.FatalLevel, 4)
  • error (zerolog.ErrorLevel, 3)
  • warn (zerolog.WarnLevel, 2)
  • info (zerolog.InfoLevel, 1)
  • debug (zerolog.DebugLevel, 0)
  • trace (zerolog.TraceLevel, -1)
// 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" }'