logging.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package middleware
  2. import (
  3. "context"
  4. "github.com/aws/smithy-go/logging"
  5. )
  6. // loggerKey is the context value key for which the logger is associated with.
  7. type loggerKey struct{}
  8. // GetLogger takes a context to retrieve a Logger from. If no logger is present on the context a logging.Nop logger
  9. // is returned. If the logger retrieved from context supports the ContextLogger interface, the context will be passed
  10. // to the WithContext method and the resulting logger will be returned. Otherwise the stored logger is returned as is.
  11. func GetLogger(ctx context.Context) logging.Logger {
  12. logger, ok := ctx.Value(loggerKey{}).(logging.Logger)
  13. if !ok || logger == nil {
  14. return logging.Nop{}
  15. }
  16. return logging.WithContext(ctx, logger)
  17. }
  18. // SetLogger sets the provided logger value on the provided ctx.
  19. func SetLogger(ctx context.Context, logger logging.Logger) context.Context {
  20. return context.WithValue(ctx, loggerKey{}, logger)
  21. }
  22. type setLogger struct {
  23. Logger logging.Logger
  24. }
  25. // AddSetLoggerMiddleware adds a middleware that will add the provided logger to the middleware context.
  26. func AddSetLoggerMiddleware(stack *Stack, logger logging.Logger) error {
  27. return stack.Initialize.Add(&setLogger{Logger: logger}, After)
  28. }
  29. func (a *setLogger) ID() string {
  30. return "SetLogger"
  31. }
  32. func (a *setLogger) HandleInitialize(ctx context.Context, in InitializeInput, next InitializeHandler) (
  33. out InitializeOutput, metadata Metadata, err error,
  34. ) {
  35. return next.HandleInitialize(SetLogger(ctx, a.Logger), in)
  36. }