【问题标题】:prevent Rails from logging email attachments防止 Rails 记录电子邮件附件
【发布时间】:2012-02-22 20:00:59
【问题描述】:

当我发送带有附件的电子邮件时,数据以十六进制记录并填满我的整个日志。有没有办法禁用附件记录?我知道我可以使用 config.action_mailer.logger = nil 禁用邮件记录。

【问题讨论】:

    标签: ruby-on-rails logging actionmailer


    【解决方案1】:

    很遗憾,如果日志级别设置为:debug(非生产环境的默认级别),则附件会包含在日志中。这意味着在生产中你应该没问题,但你的开发和登台环境在测试期间可能会膨胀。您可以拒绝整个应用程序的日志记录 (config.log_level = :info),但这显然不太理想。

    您可以配置自定义记录器:

    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
    

    这将拆分日志,但您可以将日志级别更改隔离到操作邮件程序。

    【讨论】:

    • 在 Rails 4 中,您应该使用 ActiveSupport::Logger,因为 ActiveSupport::BufferedLogger 已被贬值 (source)。
    【解决方案2】:

    Application.rb 中,您可以尝试过滤附件参数。我相信这应该可以解决问题,但我自己没有测试过

    config.filter_parameters += [:attachment]  
    

    【讨论】:

    • filter_parameters 是关于过滤发送到您网站的参数,不是吗?
    • 我的理解是并且一直是 filter_parameters 阻止该参数被打印到日志中,这样你就不会不小心将信用卡号或密码打印到日志文件中
    • 正确。但如果我渲染一个邮件视图,我认为它不会显示为 GET 或 POST 参数,因为这是在另一个方向。
    【解决方案3】:

    如果您仍希望您的日志级别处于调试状态,您可以通过覆盖 ActionMailer 的 LogSubscriber 类从日志输出中删除附件。查看您的 actionmailer gem 中的类,并进行相应调整。对于我的 Rails 4.2.10 安装,相关文件是: gems/actionmailer-4.2.10/lib/action_mailer/log_subscriber.rb

    我的模块是:

    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
    

    将其保存到 app/ 文件夹下的任何位置的 .rb 文件中,它将被包含在内。

    【讨论】:

    • 这正是问题所要求的!为了跳过编码附件但保留其他所有内容(包括边界),需要进行小幅改进:new_message &lt;&lt; line unless skip &amp;&amp; line !~ /----==_mimepart/
    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 2018-03-31
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多