【问题标题】:Filter out email addresses from ActionMailer logs从 ActionMailer 日志中过滤掉电子邮件地址
【发布时间】:2013-04-29 03:16:58
【问题描述】:
在 Rails 中通过 Actionmailer 发送电子邮件时,它会记录如下内容:
Sent mail to example@example.com (72ms)
Rendered mailer/_header.html.erb (0.0ms)
...
我想从日志 ala 参数过滤中过滤电子邮件
Sent mail to [FILTERED] (72ms)
Rendered mailer/_header.html.erb (0.0ms)
...
有没有一种干净的方法可以做到这一点?或者,不记录整个第一行也可以。
【问题讨论】:
标签:
ruby-on-rails
ruby-on-rails-3
actionmailer
【解决方案1】:
在 Rails 源代码中./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 没有提供过滤电子邮件的方法,因此您可以:
- fork rails,删除此信息,然后使用您的 fork 版本的 rails。
- 编辑此代码,添加一些过滤器,然后发出拉取请求。
【解决方案2】:
你可以为你当前的动作邮件做一个猴子补丁:
- 为您的 rails 版本查找 gem 源代码(在我的情况下,它位于 ~/.rvm/gems/xxx@railsx/gems/actionmailer-x.x.x/lib/action_mailer 中
- 查找包含“Sent mail to”的方法
-
在“lib”目录中创建一个文件,内容如下(复制并粘贴第 2 步中的代码并将“recipients”更改为“[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
对于我的 action_mailer 版本,代码如下:
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