log.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. "github.com/smallstep/certificates/logging"
  9. )
  10. // StackTracedError is the set of errors implementing the StackTrace function.
  11. //
  12. // Errors implementing this interface have their stack traces logged when passed
  13. // to the Error function of this package.
  14. type StackTracedError interface {
  15. error
  16. StackTrace() errors.StackTrace
  17. }
  18. // Error adds to the response writer the given error if it implements
  19. // logging.ResponseLogger. If it does not implement it, then writes the error
  20. // using the log package.
  21. func Error(rw http.ResponseWriter, err error) {
  22. rl, ok := rw.(logging.ResponseLogger)
  23. if !ok {
  24. return
  25. }
  26. rl.WithFields(map[string]interface{}{
  27. "error": err,
  28. })
  29. if os.Getenv("STEPDEBUG") != "1" {
  30. return
  31. }
  32. e, ok := err.(StackTracedError)
  33. if !ok {
  34. e, ok = errors.Cause(err).(StackTracedError)
  35. }
  36. if ok {
  37. rl.WithFields(map[string]interface{}{
  38. "stack-trace": fmt.Sprintf("%+v", e.StackTrace()),
  39. })
  40. }
  41. }
  42. // EnabledResponse log the response object if it implements the EnableLogger
  43. // interface.
  44. func EnabledResponse(rw http.ResponseWriter, v interface{}) {
  45. type enableLogger interface {
  46. ToLog() (interface{}, 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.(logging.ResponseLogger); ok {
  55. rl.WithFields(map[string]interface{}{
  56. "response": out,
  57. })
  58. }
  59. }
  60. }