recover.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Package recover provides recovery for specific routes or for the whole app via middleware. See _examples/recover
  2. package recover
  3. import (
  4. "fmt"
  5. "runtime"
  6. "strconv"
  7. "github.com/kataras/iris/context"
  8. )
  9. func init() {
  10. context.SetHandlerName("iris/middleware/recover.*", "iris.recover")
  11. }
  12. func getRequestLogs(ctx *context.Context) string {
  13. var status, ip, method, path string
  14. status = strconv.Itoa(ctx.GetStatusCode())
  15. path = ctx.Path()
  16. method = ctx.Method()
  17. ip = ctx.RemoteAddr()
  18. // the date should be logged by iris' Logger, so we skip them
  19. return fmt.Sprintf("%v %s %s %s", status, path, method, ip)
  20. }
  21. // New returns a new recover middleware,
  22. // it recovers from panics and logs
  23. // the panic message to the application's logger "Warn" level.
  24. func New() context.Handler {
  25. return func(ctx *context.Context) {
  26. defer func() {
  27. if err := recover(); err != nil {
  28. if ctx.IsStopped() {
  29. return
  30. }
  31. var stacktrace string
  32. for i := 1; ; i++ {
  33. _, f, l, got := runtime.Caller(i)
  34. if !got {
  35. break
  36. }
  37. stacktrace += fmt.Sprintf("%s:%d\n", f, l)
  38. }
  39. // when stack finishes
  40. logMessage := fmt.Sprintf("Recovered from a route's Handler('%s')\n", ctx.HandlerName())
  41. logMessage += fmt.Sprintf("At Request: %s\n", getRequestLogs(ctx))
  42. logMessage += fmt.Sprintf("Trace: %s\n", err)
  43. logMessage += fmt.Sprintf("\n%s", stacktrace)
  44. ctx.Application().Logger().Warn(logMessage)
  45. ctx.StopWithStatus(500)
  46. }
  47. }()
  48. ctx.Next()
  49. }
  50. }