Filter email addresses from ActionMailer logs

When sending emails through the Actionmailer in Rails, it writes something like:

Sent mail to example@example.com (72ms) Rendered mailer/_header.html.erb (0.0ms) ... 

I would like to filter emails by filtering logs ala parameters

 Sent mail to [FILTERED] (72ms) Rendered mailer/_header.html.erb (0.0ms) ... 

Is there a clean way to do this? Alternatively, not registering the entire first row will be OK.

+6
source share
2 answers

You can make a monkey patch for your current mail program:

  • find the gem source code for your version of the rails (in my case it is in ~ / .rvm / gems / xxx@railsx / gems / actionmailer-xxx / lib / action_mailer
  • find the method that contains the message "Sent an email"
  • Create a file in your "lib" directory with this content (copy and paste the code from step 2 and change the "recipients" to "[FILTERED]":

     module ActionMailer class LogSubscriber < ActiveSupport::LogSubscriber def deliver(event) return unless logger.info? #recipients = Array(event.payload[:to]).join(', ') info("\nSent mail to [FILTERED] (#{event.duration.round(1)}ms)") debug(event.payload[:mail]) end end end 

For my version of action_mailer, the code would look like this:

 def deliver!(mail = @mail) raise "no mail object available for delivery!" unless mail unless logger.nil? logger.info "Sent mail to [FILTERED]" # instead of original logger.info "Sent mail to #{Array(recipients).join(', ')}" logger.debug "\n#{mail.encoded}" end begin __send__("perform_delivery_#{delivery_method}", mail) if perform_deliveries rescue Exception => e # Net::SMTP errors or sendmail pipe errors raise e if raise_delivery_errors end return mail end 
0
source

In Rails, the source code ./actionmailer/lib/action_mailer/log_subscriber.rb :

 module ActionMailer class LogSubscriber < ActiveSupport::LogSubscriber def deliver(event) return unless logger.info? recipients = Array(event.payload[:to]).join(', ') info("\nSent mail to #{recipients} (#{event.duration.round(1)}ms)") debug(event.payload[:mail]) end def receive(event) return unless logger.info? info("\nReceived mail (#{event.duration.round(1)}ms)") debug(event.payload[:mail]) end def logger ActionMailer::Base.logger end end end 

Rails does not provide an email filtering method, so you can:

  • fork rails, delete this information and use a forked version of the rails.
  • edit this code, add a filter and make a transfer request.
0
source

Source: https://habr.com/ru/post/943849/


All Articles