You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.9 KiB

1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
  1. module Semantic
  2. # use the Zeitwerk autoloader to reattach_appender for development autoreloading feature
  3. class DevLoader
  4. def initialize(session_key)
  5. @session_key = session_key
  6. force_preload_module
  7. once_and_reload do
  8. append_ansi_formatter
  9. register_log_subscriber
  10. end
  11. # FIXME: when final
  12. # Rails.logger.level = :error
  13. end
  14. private
  15. def once_and_reload(&)
  16. yield
  17. Rails.autoloaders.main.on_load('ApplicationController', &)
  18. end
  19. def force_preload_module
  20. self.class.module_parent.constants.each { |const| self.class.module_parent.const_get(const) }
  21. end
  22. def append_ansi_formatter
  23. SemanticLogger.clear_appenders!
  24. formatter = Semantic::AnsiFormatter.new
  25. SemanticLogger.add_appender(io: $stdout,
  26. formatter:,
  27. filter: ->(log) { !formatter.reject(log) })
  28. end
  29. def register_log_subscriber
  30. reset_subscribers
  31. register_to_action_controller(:start_processing)
  32. register_to_action_controller(:process_action, :finish_processing)
  33. register_to_action_controller(:redirect_to)
  34. %i[send_file send_data halted_callback unpermitted_parameters send_stream write_fragment
  35. read_fragment expire_fragment exist_fragment?].each do |hook|
  36. register_to_action_controller(hook, :any_hook)
  37. end
  38. end
  39. def register_to_action_controller(hook, method = hook)
  40. @subscribers << ActiveSupport::Notifications.subscribe("#{hook}.action_controller") do |event|
  41. @log_subscriber.send(method, event)
  42. end
  43. end
  44. def reset_subscribers
  45. if defined?(@subscribers)
  46. @subscribers.each { |sub| ActiveSupport::Notifications.unsubscribe(sub) }
  47. @subscribers.clear
  48. else
  49. @subscribers = []
  50. end
  51. @log_subscriber = Semantic::LogSubscriber.new(@session_key)
  52. end
  53. end
  54. end