Request Logging

The application logger we’ve seen above it’s used to log application-releated information and errors. At the other hand, the Access Logger, we see below, is used to log the incoming HTTP requests and responses.

  1. package main
  2. import (
  3. "os"
  4. "github.com/kataras/iris/v12"
  5. "github.com/kataras/iris/v12/middleware/accesslog"
  6. )
  7. // Read the example and its comments carefully.
  8. func makeAccessLog() *accesslog.AccessLog {
  9. // Initialize a new access log middleware.
  10. ac := accesslog.File("./access.log")
  11. // Remove this line to disable logging to console:
  12. ac.AddOutput(os.Stdout)
  13. // The default configuration:
  14. ac.Delim = '|'
  15. ac.TimeFormat = "2006-01-02 15:04:05"
  16. ac.Async = false
  17. ac.IP = true
  18. ac.BytesReceivedBody = true
  19. ac.BytesSentBody = true
  20. ac.BytesReceived = false
  21. ac.BytesSent = false
  22. ac.BodyMinify = true
  23. ac.RequestBody = true
  24. ac.ResponseBody = false
  25. ac.KeepMultiLineError = true
  26. ac.PanicLog = accesslog.LogHandler
  27. // Default line format if formatter is missing:
  28. // Time|Latency|Code|Method|Path|IP|Path Params Query Fields|Bytes Received|Bytes Sent|Request|Response|
  29. //
  30. // Set Custom Formatter:
  31. ac.SetFormatter(&accesslog.JSON{
  32. Indent: " ",
  33. HumanTime: true,
  34. })
  35. // ac.SetFormatter(&accesslog.CSV{})
  36. // ac.SetFormatter(&accesslog.Template{Text: "{{.Code}}"})
  37. return ac
  38. }
  39. func main() {
  40. ac := makeAccessLog()
  41. defer ac.Close() // Close the underline file.
  42. app := iris.New()
  43. // Register the middleware (UseRouter to catch http errors too).
  44. app.UseRouter(ac.Handler)
  45. app.Get("/", indexHandler)
  46. app.Listen(":8080")
  47. }
  48. func indexHandler(ctx iris.Context) {
  49. ctx.WriteString("OK")
  50. }

Read more examples at: _examples/logging/request-logger.