log.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Package log implements API-related logging helpers.
  2. package log
  3. import (
  4. "context"
  5. "fmt"
  6. "log/slog"
  7. "net/http"
  8. "os"
  9. "github.com/pkg/errors"
  10. )
  11. // ErrorKey is the logging attribute key for error values.
  12. const ErrorKey = "error"
  13. type loggerKey struct{}
  14. // NewContext creates a new context with the given slog.Logger.
  15. func NewContext(ctx context.Context, logger *slog.Logger) context.Context {
  16. return context.WithValue(ctx, loggerKey{}, logger)
  17. }
  18. // FromContext returns the logger from the given context.
  19. func FromContext(ctx context.Context) (l *slog.Logger, ok bool) {
  20. l, ok = ctx.Value(loggerKey{}).(*slog.Logger)
  21. return
  22. }
  23. // StackTracedError is the set of errors implementing the StackTrace function.
  24. //
  25. // Errors implementing this interface have their stack traces logged when passed
  26. // to the Error function of this package.
  27. type StackTracedError interface {
  28. error
  29. StackTrace() errors.StackTrace
  30. }
  31. type fieldCarrier interface {
  32. WithFields(map[string]any)
  33. Fields() map[string]any
  34. }
  35. // Error adds to the response writer the given error if it implements
  36. // logging.ResponseLogger. If it does not implement it, then writes the error
  37. // using the log package.
  38. func Error(rw http.ResponseWriter, r *http.Request, err error) {
  39. ctx := r.Context()
  40. if logger, ok := FromContext(ctx); ok && err != nil {
  41. logger.ErrorContext(ctx, "request failed", slog.Any(ErrorKey, err))
  42. }
  43. fc, ok := rw.(fieldCarrier)
  44. if !ok {
  45. return
  46. }
  47. fc.WithFields(map[string]any{
  48. "error": err,
  49. })
  50. if os.Getenv("STEPDEBUG") != "1" {
  51. return
  52. }
  53. var st StackTracedError
  54. if errors.As(err, &st) {
  55. fc.WithFields(map[string]any{
  56. "stack-trace": fmt.Sprintf("%+v", st.StackTrace()),
  57. })
  58. }
  59. }
  60. // EnabledResponse log the response object if it implements the EnableLogger
  61. // interface.
  62. func EnabledResponse(rw http.ResponseWriter, r *http.Request, v any) {
  63. type enableLogger interface {
  64. ToLog() (any, error)
  65. }
  66. if el, ok := v.(enableLogger); ok {
  67. out, err := el.ToLog()
  68. if err != nil {
  69. Error(rw, r, err)
  70. return
  71. }
  72. if rl, ok := rw.(fieldCarrier); ok {
  73. rl.WithFields(map[string]any{
  74. "response": out,
  75. })
  76. }
  77. }
  78. }