为什么Rails.logger在开发和测试中写入相同的日志文件?

时间:2017-06-28 18:49:57

标签: ruby-on-rails ruby logging

我有以下模型测试:

  describe 'Checking for errors' do
    it 'should check for any jobs that have errors and log them' do
      logger = Logger.new('log/go_job_errors_test.log')
      code_location = create(:code_location_with_best_code_set)
      code_location.jobs << create(:complete_job, status: 3, exception: 'I failed to complete')
      CodeLocationJobFeeder.create(code_location_id: code_location.id, url: code_location.repository.url, status: 2)
      CodeLocationJobFeeder.check_for_errors(1)
      logger.expects(:info).with("I failed to complete")
    end

使用以下型号代码:

def check_for_errors(amount)
  processed.limit(amount).each do |code_location_job_feeder|
    code_location = CodeLocation.includes(:jobs).find(code_location_job_feeder.code_location_id)
    log_error(code_location) unless code_location.jobs.last.status != 3
  end
end

private

def log_error(code_location)
  logger = Logger.new('log/go_job_errors.log')
  failed_job = code_location.jobs.last
  logger.info do
    "Job #{failed_job.id} with code location: #{code_location.id} failed. Exception: #{failed_job.exception}"
  end
end

测试的要点是当我执行CodeLocationJobFeeder.check_for_errors时,我将有一个单独的日志文件,它将告诉我有关某些错误的所有信息。这在开发中工作正常,我得到了我想要的文件。但是,当我运行测试时,我会在log/go_job_errors_test.loglog/go_job_errors.log输出以下输出:

log/go_job_errors.log

[2017-06-28T18:23:46.164141 #29604]  INFO -- : Job 40 with code location: 93 failed. Exception: I failed to complete

这是我想要的内容但是在错误的文件中。这是第二个文件:

 log/go_job_error_test.log

 # Logfile created on 2017-06-28 18:40:59 +0000 by logger.rb/47272

内容错误的正确文件。

我一直试图申请这个s.o.回答Logger test,但似乎没有太大的效果。有人可以帮助指出我做错了吗?

1 个答案:

答案 0 :(得分:1)

这一行&#34; Logger.new(&#39; log / go_job_errors.log&#39;)&#34;在模型中指示将模型错误记录到此文件&#39; log / go_job_errors.log&#39;。无论环境如何,模型错误总是记录在这里&#39; log / go_job_errors.log&#39;

在您的测试中,您从这一行&#39; Logger.new(&#39; log / go_job_errors_test.log&#39;)&#39;开始,此行创建一个新的日志文件。当您的测试调用模型时,模型会调用&#39; log_error(code_location)&#39;,但该方法仅记录到&#39; log / go_job_errors.log&#39;。