Ruby on Rails中的日志轮换/清除

10

如何在Ruby on Rails中设置自动清理test.log和development.log日志?

是否有设置可以在服务器启动和测试运行时自动删除dev和test日志的选项?


“Cleanup”具体指什么? - cakeforcerberus
5个回答

19

Ruby日志记录器可以帮助你 - 它默认提供轮换选项。

这是我所做的:

environment.rb中,我们定义自己的日志记录器。

new_logger = Logger.new(File.join(RAILS_ROOT, "log", "new_logger_#{RAILS_ENV}.log"), 'daily')
new_logger.formatter = Logger::Formatter.new

这将创建一个带有格式化程序的我们自己的记录器(以便您获得时间戳等),每个环境使用一个,每天轮换。

然后,在初始化块中,我们要求Rails使用此记录器。

Rails::Initializer.run do |config|

  config.active_record.logger = new_logger
  config.action_controller.logger = new_logger

  #snip
end
你显然可以看到这里的优势,可以为active_recordaction_controller使用不同的记录器——有时非常有用!

4
注意:在Rails 3中,你的“初始化块”位于development.rb、production.rb等文件中。 - bcoughlan
1
此外,在Rails 3中,您的RAILS_ROOTRails.root,而RAILS_ENVRails.env。看起来Rails社区不再使用大写锁定键了? - Ziggy

16

rake log:clear是一个rake任务,它会将所有匹配 log/*.log 的文件截断为零字节。 你可以在服务器启动和运行测试任务中调用它。


+1 给 Rake 任务。同样,您也可以使用 File.delete() 手动删除磁盘上的所有日志文件(请确保还删除了以 .0.1 等结尾的任何回滚文件)。然后,您可以使用 @logger.reopen 重置记录器,它将重新创建日志文件。 - abhchand

1
所有的脚本/服务器都只是一个Ruby脚本,我相信你可以修改它来做一些类似的事情:
#!/usr/bin/env ruby
require 'fileutils'
FileUtils.rm File.join(File.dirname(__FILE__), log, *.log)
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/server'

0
经过实验,我发现Rails初始化器在正确的时间点加载,您可以使用标准的Ruby File类截断文件。我将其放置在config/initializers/truncate_logs_on_server_start.rb中:
if MyRailsApp::Application.config.truncate_logs_on_server_start
  # Making an assumption here that we're logging to a file...
  File.open("log/#{ENV["RAILS_ENV"]}.log", "w") do |log_file|
    log_file.puts("Initializer truncate_logs_on_server_start reset the log file")
    log_file.puts
  end
end

您只需要在application.rb文件和各个环境中设置MyRailsApp::Application.config.truncate_logs_on_server_start即可。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接