log.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Package log implements API-related logging helpers.
  2. package log
  3. import (
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "github.com/pkg/errors"
  8. )
  9. // StackTracedError is the set of errors implementing the StackTrace function.
  10. //
  11. // Errors implementing this interface have their stack traces logged when passed
  12. // to the Error function of this package.
  13. type StackTracedError interface {
  14. error
  15. StackTrace() errors.StackTrace
  16. }
  17. type fieldCarrier interface {
  18. WithFields(map[string]any)
  19. Fields() map[string]any
  20. }
  21. // Error adds to the response writer the given error if it implements
  22. // logging.ResponseLogger. If it does not implement it, then writes the error
  23. // using the log package.
  24. func Error(rw http.ResponseWriter, err error) {
  25. fc, ok := rw.(fieldCarrier)
  26. if !ok {
  27. return
  28. }
  29. fc.WithFields(map[string]any{
  30. "error": err,
  31. })
  32. if os.Getenv("STEPDEBUG") != "1" {
  33. return
  34. }
  35. var st StackTracedError
  36. if errors.As(err, &st) {
  37. fc.WithFields(map[string]any{
  38. "stack-trace": fmt.Sprintf("%+v", st.StackTrace()),
  39. })
  40. }
  41. }
  42. // EnabledResponse log the response object if it implements the EnableLogger
  43. // interface.
  44. func EnabledResponse(rw http.ResponseWriter, v any) {
  45. type enableLogger interface {
  46. ToLog() (any, error)
  47. }
  48. if el, ok := v.(enableLogger); ok {
  49. out, err := el.ToLog()
  50. if err != nil {
  51. Error(rw, err)
  52. return
  53. }
  54. if rl, ok := rw.(fieldCarrier); ok {
  55. rl.WithFields(map[string]any{
  56. "response": out,
  57. })
  58. }
  59. }
  60. }