Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Log pry command? #2222

Open
huguesbr opened this issue Nov 24, 2021 · 1 comment
Open

Log pry command? #2222

huguesbr opened this issue Nov 24, 2021 · 1 comment

Comments

@huguesbr
Copy link

Not an issue but a question/request?

Is it possible to hook into pry to log any command sent and the (string) result of a command?

Thank you

@huguesbr
Copy link
Author

Answering my own question, I guess more related to pry-rails but

class LoggingReadline
  delegate :completion_proc, :completion_proc=, to: Readline

  def readline(prompt)
    Readline.readline(prompt).tap do |user_input|
      logger.info(user_input)
    end
  end

  private

  def logger
    @logger ||= Logger.new('log/console.log')
  end
end

Pry.config.input = LoggingReadline.new

source: https://www.hardscrabble.net/2015/how-to-log-all-input-in-your-pry-rails-console/

I've wrote a little class to do handle this:

class PryLogger
  class LoggingReadline
    attr_accessor :logger
    delegate :completion_proc, :completion_proc=, to: Readline

    def initialize(logger:)
      self.logger = logger
    end

    def readline(prompt)
      Readline.readline(prompt).tap do |user_input|
        self.logger.info("console input: #{user_input}")
      end
    end
  end

  class LoggedIO
    attr_accessor :io, :logger

    def initialize(io, logger:)
      self.io = io
      self.logger = logger
    end

    def method_missing(method_name, *args)
      if method_name == :print
        self.logger.info("console output: #{args.first}")
      end
      io.send(method_name, *args)
    end
  end

  def self.configure(pry_config, input_logger: nil, output_logger: nil)
    pry_config.input = LoggingReadline.new(logger: input_logger) if input_logger
    pry_config.output = LoggedIO.new($stdout, logger: output_logger) if output_logger
  end
end

usage:

# config/initializers/pry.rb

Pry.configure do |config|
  PryLogger.configure(config, input_logger: Rails.logger, output_logger: Rails.logger)
end

Hope it helps other

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant