4
0

log.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. var st StackTracedError
  33. if !errors.As(err, &st) {
  34. rl.WithFields(map[string]interface{}{
  35. "stack-trace": fmt.Sprintf("%+v", st.StackTrace()),
  36. })
  37. }
  38. }
  39. // EnabledResponse log the response object if it implements the EnableLogger
  40. // interface.
  41. func EnabledResponse(rw http.ResponseWriter, v interface{}) {
  42. type enableLogger interface {
  43. ToLog() (interface{}, error)
  44. }
  45. if el, ok := v.(enableLogger); ok {
  46. out, err := el.ToLog()
  47. if err != nil {
  48. Error(rw, err)
  49. return
  50. }
  51. if rl, ok := rw.(logging.ResponseLogger); ok {
  52. rl.WithFields(map[string]interface{}{
  53. "response": out,
  54. })
  55. }
  56. }
  57. }