2022-03-22 12:31:18 +00:00
|
|
|
// Package log implements API-related logging helpers.
|
|
|
|
package log
|
|
|
|
|
|
|
|
import (
|
2022-03-30 08:22:22 +00:00
|
|
|
"fmt"
|
2022-03-22 12:31:18 +00:00
|
|
|
"net/http"
|
2022-03-30 08:22:22 +00:00
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2022-03-22 12:31:18 +00:00
|
|
|
)
|
|
|
|
|
2022-03-30 08:22:22 +00:00
|
|
|
// StackTracedError is the set of errors implementing the StackTrace function.
|
|
|
|
//
|
|
|
|
// Errors implementing this interface have their stack traces logged when passed
|
|
|
|
// to the Error function of this package.
|
|
|
|
type StackTracedError interface {
|
|
|
|
error
|
|
|
|
|
|
|
|
StackTrace() errors.StackTrace
|
|
|
|
}
|
|
|
|
|
2022-11-17 14:04:21 +00:00
|
|
|
type fieldCarrier interface {
|
|
|
|
WithFields(map[string]any)
|
|
|
|
}
|
|
|
|
|
2022-03-22 12:31:18 +00:00
|
|
|
// Error adds to the response writer the given error if it implements
|
|
|
|
// logging.ResponseLogger. If it does not implement it, then writes the error
|
|
|
|
// using the log package.
|
|
|
|
func Error(rw http.ResponseWriter, err error) {
|
2022-11-17 14:04:21 +00:00
|
|
|
fc, ok := rw.(fieldCarrier)
|
2022-03-30 08:22:22 +00:00
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-11-17 14:04:21 +00:00
|
|
|
fc.WithFields(map[string]any{
|
2022-03-30 08:22:22 +00:00
|
|
|
"error": err,
|
|
|
|
})
|
|
|
|
|
|
|
|
if os.Getenv("STEPDEBUG") != "1" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-22 07:04:31 +00:00
|
|
|
var st StackTracedError
|
2022-11-17 11:29:54 +00:00
|
|
|
if errors.As(err, &st) {
|
2022-11-17 14:04:21 +00:00
|
|
|
fc.WithFields(map[string]any{
|
2022-09-22 07:04:31 +00:00
|
|
|
"stack-trace": fmt.Sprintf("%+v", st.StackTrace()),
|
2022-03-22 12:31:18 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// EnabledResponse log the response object if it implements the EnableLogger
|
|
|
|
// interface.
|
2022-11-17 14:04:21 +00:00
|
|
|
func EnabledResponse(rw http.ResponseWriter, v any) {
|
2022-03-22 12:31:18 +00:00
|
|
|
type enableLogger interface {
|
2022-11-17 14:04:21 +00:00
|
|
|
ToLog() (any, error)
|
2022-03-22 12:31:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if el, ok := v.(enableLogger); ok {
|
|
|
|
out, err := el.ToLog()
|
|
|
|
if err != nil {
|
|
|
|
Error(rw, err)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-11-17 14:04:21 +00:00
|
|
|
if rl, ok := rw.(fieldCarrier); ok {
|
|
|
|
rl.WithFields(map[string]any{
|
2022-03-22 12:31:18 +00:00
|
|
|
"response": out,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|