Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent Rails from logging email attachments

Tags:

When I send an email with an attachment the data is logged in hex and fills up my whole log. Is there a way to disable logging of attachments?

I know I can disable mailer logging with config.action_mailer.logger = nil.

like image 497
m33lky Avatar asked Jan 31 '12 02:01

m33lky


2 Answers

Unfortunately, the attachments are included in the logs if the logging level is set to :debug, the default level for non-production environments. This means that in production you should be fine, but your dev and staging environments could bloat during testing. You could turn down logging for your entire app (config.log_level = :info), but this is obviously less than ideal.

You can configure a custom logger:

config.action_mailer.logger = ActiveSupport::BufferedLogger.new("mailer.log")
config.action_mailer.logger.level = ActiveSupport::BufferedLogger::Severity::INFO

Rails 4

config.action_mailer.logger = ActiveSupport::Logger.new("mailer.log")
config.action_mailer.logger.level = ActiveSupport::Logger::Severity::INFO

This will split the log, but you can isolate the logging level change to the action mailer.

like image 102
MikeG Avatar answered Oct 06 '22 00:10

MikeG


If you still want your log level to be debug, you can remove the attachments from the log output by overriding ActionMailer's LogSubscriber class. Look at the class in your actionmailer gem, and adjust accordingly. For my Rails 4.2.10 install, the relevant file is: gems/actionmailer-4.2.10/lib/action_mailer/log_subscriber.rb

My module is:

module ActionMailer
  class LogSubscriber < ActiveSupport::LogSubscriber
    def deliver(event)
      info do
        recipients = Array(event.payload[:to]).join(', ')
        "\nSent mail to #{recipients}, Subject: #{event.payload[:subject]}, on #{event.payload[:date]} (#{event.duration.round(1)}ms)"
      end

      debug { remove_attachments(event.payload[:mail]) }
    end

  def remove_attachments(message)
    new_message = ''
    skip = false
    message.each_line do |line|
      new_message << line unless skip
      skip = true if line =~ /Content-Disposition: attachment;/
      skip = false if skip && line =~ /----==_mimepart/
    end
    new_message
  end
 end
end

Save this to an .rb file anywhere under your app/ folder and it will be included.

like image 29
Brent Avatar answered Oct 06 '22 00:10

Brent