log.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. // AsStackTracedError attempts to return the input error cast to a
  19. // StackTracedError interface.
  20. func AsStackTracedError(err error) (StackTracedError, bool) {
  21. //nolint:errorlint // ignore type assertion warning. casting to interface is hard.
  22. if st, ok := err.(StackTracedError); ok {
  23. return st, ok
  24. }
  25. return nil, false
  26. }
  27. // Error adds to the response writer the given error if it implements
  28. // logging.ResponseLogger. If it does not implement it, then writes the error
  29. // using the log package.
  30. func Error(rw http.ResponseWriter, err error) {
  31. rl, ok := rw.(logging.ResponseLogger)
  32. if !ok {
  33. return
  34. }
  35. rl.WithFields(map[string]interface{}{
  36. "error": err,
  37. })
  38. if os.Getenv("STEPDEBUG") != "1" {
  39. return
  40. }
  41. e, ok := AsStackTracedError(err)
  42. if !ok {
  43. //nolint:errorlint // ignore type assertion warning. casting to interface is hard.
  44. e, ok = errors.Cause(err).(StackTracedError)
  45. }
  46. if ok {
  47. rl.WithFields(map[string]interface{}{
  48. "stack-trace": fmt.Sprintf("%+v", e.StackTrace()),
  49. })
  50. }
  51. }
  52. // EnabledResponse log the response object if it implements the EnableLogger
  53. // interface.
  54. func EnabledResponse(rw http.ResponseWriter, v interface{}) {
  55. type enableLogger interface {
  56. ToLog() (interface{}, error)
  57. }
  58. if el, ok := v.(enableLogger); ok {
  59. out, err := el.ToLog()
  60. if err != nil {
  61. Error(rw, err)
  62. return
  63. }
  64. if rl, ok := rw.(logging.ResponseLogger); ok {
  65. rl.WithFields(map[string]interface{}{
  66. "response": out,
  67. })
  68. }
  69. }
  70. }