log_subscriber.rb 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. require "active_support/log_subscriber"
  2. module Dotenv
  3. # Logs instrumented events
  4. #
  5. # Usage:
  6. # require "active_support/notifications"
  7. # require "dotenv/log_subscriber"
  8. # Dotenv.instrumenter = ActiveSupport::Notifications
  9. #
  10. class LogSubscriber < ActiveSupport::LogSubscriber
  11. attach_to :dotenv
  12. def logger
  13. Dotenv::Rails.logger
  14. end
  15. def load(event)
  16. env = event.payload[:env]
  17. info "Loaded #{color_filename(env.filename)}"
  18. end
  19. def update(event)
  20. diff = event.payload[:diff]
  21. changed = diff.env.keys.map { |key| color_var(key) }
  22. debug "Set #{changed.to_sentence}" if diff.any?
  23. end
  24. def save(event)
  25. info "Saved a snapshot of #{color_env_constant}"
  26. end
  27. def restore(event)
  28. diff = event.payload[:diff]
  29. removed = diff.removed.keys.map { |key| color(key, :RED) }
  30. restored = (diff.changed.keys + diff.added.keys).map { |key| color_var(key) }
  31. if removed.any? || restored.any?
  32. info "Restored snapshot of #{color_env_constant}"
  33. debug "Unset #{removed.to_sentence}" if removed.any?
  34. debug "Restored #{restored.to_sentence}" if restored.any?
  35. end
  36. end
  37. private
  38. def color_filename(filename)
  39. color(Pathname.new(filename).relative_path_from(Dotenv::Rails.root.to_s).to_s, :YELLOW)
  40. end
  41. def color_var(name)
  42. color(name, :CYAN)
  43. end
  44. def color_env_constant
  45. color("ENV", :GREEN)
  46. end
  47. end
  48. end