将 vs 记录器放入 Rails rake 任务中

发布于 2024-08-21 23:17:16 字数 236 浏览 2 评论 0原文

在 rake 任务中,如果我使用 put 命令,那么我会在控制台上看到输出。但是,当应用程序部署在生产环境中时,我不会在日志文件中看到该消息。

但是,如果我说 Rails.logger.info 那么在开发模式下我在控制台上看不到任何内容。我需要去日志文件并跟踪它。

理想情况下,我希望使用 Rails.logger.info 并在 rake 任务内的开发模式下,记录器的输出也应发送到控制台。

有办法实现吗?

In a rake task if I use puts command then I see the output on console. However I will not see that message in log file when app is deployed on production.

However if I say Rails.logger.info then in development mode I see nothing on console. I need to go to log file and tail that.

I would ideally like to use Rails.logger.info and in development mode inside the rake task, the output from logger should also be sent to console.

Is there a way to achieve that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

失退 2024-08-28 23:17:16

将其放入 application.rb 中,或放在 rake 任务初始化代码中

if defined?(Rails) && (Rails.env == 'development')
  Rails.logger = Logger.new(STDOUT)
end

这是 Rails 3 代码。请注意,这将覆盖 development.log 的日志记录。如果您想要 STDOUTdevelopment.log 您将需要一个包装函数。

如果您只想在 Rails 控制台中实现此行为,请将相同的代码块放入 ~/.irbrc 中。

Put this in application.rb, or in a rake task initialize code

if defined?(Rails) && (Rails.env == 'development')
  Rails.logger = Logger.new(STDOUT)
end

This is Rails 3 code. Note that this will override logging to development.log. If you want both STDOUT and development.log you'll need a wrapper function.

If you'd like this behaviour only in the Rails console, place the same block of code in your ~/.irbrc.

疯了 2024-08-28 23:17:16

您可以创建一个新的 rake 任务来使其发挥作用。

desc "switch logger to stdout"
task :to_stdout => [:environment] do
 Rails.logger = Logger.new(STDOUT)
end

这样,当您执行 rake 任务时,您可以首先添加 to_stdout 以获取 stdout 日志消息,或者不包含它以将消息发送到默认日志文件

rake to_stdout some_task

You could create a new rake task to get this to work.

desc "switch logger to stdout"
task :to_stdout => [:environment] do
 Rails.logger = Logger.new(STDOUT)
end

This way when you execute your rake task you can add to_stdout first to get stdout log messages or don't include it to have messages sent to the default log file

rake to_stdout some_task
初心 2024-08-28 23:17:16

对于 Rails 4 及更高版本的代码

,您可以使用 Logger 广播

如果您想在开发模式下获取 rake 任务的 STDOUT 和文件日志记录,可以将此代码添加到 config/environments/development.rb 中:

  if File.basename($0) == 'rake'
    # http://stackoverflow.com/questions/2246141/puts-vs-logger-in-rails-rake-tasks
    log_file     = Rails.root.join("log", "#{Rails.env}.log")
    Rails.logger = ActiveSupport::Logger.new(log_file)
    Rails.logger.extend(ActiveSupport::Logger.broadcast(ActiveSupport::Logger.new(STDOUT)))
  end

测试

这是一个小的 Rake 任务来测试上述代码:

# lib/tasks/stdout_and_log.rake
namespace :stdout_and_log do
  desc "Test if Rails.logger outputs to STDOUT and log file"
  task :test => :environment do
    puts "HELLO FROM PUTS"
    Rails.logger.info "HELLO FROM LOGGER"
  end
end

运行 rake stdout_and_log:test 输出

HELLO FROM PUTS
HELLO FROM LOGGER

HELLO FROM LOGGER

添加到 log/development.log 中。

运行 rake stdout_and_log:test RAILS_ENV=product 输出

HELLO FROM PUTS

HELLO FROM LOGGER

添加到 log/production.log 中。

Code

For Rails 4 and newer, you can use Logger broadcast.

If you want to get both STDOUT and file logging for rake tasks in development mode, you can add this code into config/environments/development.rb :

  if File.basename($0) == 'rake'
    # http://stackoverflow.com/questions/2246141/puts-vs-logger-in-rails-rake-tasks
    log_file     = Rails.root.join("log", "#{Rails.env}.log")
    Rails.logger = ActiveSupport::Logger.new(log_file)
    Rails.logger.extend(ActiveSupport::Logger.broadcast(ActiveSupport::Logger.new(STDOUT)))
  end

Test

Here's a small Rake task to test the above code :

# lib/tasks/stdout_and_log.rake
namespace :stdout_and_log do
  desc "Test if Rails.logger outputs to STDOUT and log file"
  task :test => :environment do
    puts "HELLO FROM PUTS"
    Rails.logger.info "HELLO FROM LOGGER"
  end
end

Running rake stdout_and_log:test outputs

HELLO FROM PUTS
HELLO FROM LOGGER

while

HELLO FROM LOGGER

has been added to log/development.log.

Running rake stdout_and_log:test RAILS_ENV=production outputs

HELLO FROM PUTS

while

HELLO FROM LOGGER

has been added to log/production.log.

抽个烟儿 2024-08-28 23:17:16

Rake 任务由用户在命令行上运行。他们需要立即了解的任何内容(“已处理的 5 行”)都应该使用 puts 在终端上输出。

需要为后代保留的任何内容(“已向 [电子邮件受保护] 发送警告电子邮件") 应发送到 Rails.logger

Rake tasks are run by a user, on a command-line. Anything they need to know right away ("processed 5 rows") should be output on the terminal with puts.

Anything that needs to be kept for posterity ("sent warning email to [email protected]") should be sent to the Rails.logger.

只怪假的太真实 2024-08-28 23:17:16

我想说使用 Rails.logger.info 是正确的方法。

您将无法在服务器控制台中看到它,因为它不会通过服务器运行。只需打开一个新控制台并 tail -f 日志文件,就可以了。

许多用户都知道 UNIX®
命令“tail”,可用于
显示大文本的最后几行
文件。这对于查看很有用
日志文件等

在某些情况下甚至更有用,
是“tail”的“-f”参数
命令。这会导致尾巴“跟随”
文件的输出。最初,
响应将与
“尾巴”本身 - 最后几行
将显示文件的内容。
但是,该命令不返回
到提示符,然后继续
“关注”该文件。当额外
行被添加到文件中,它们将
会显示在终端上。这是
对于查看日志文件非常有用,或者
任何其他可能附加的文件
随着时间的推移。输入“man tail”了解更多
这条尾巴和其他尾巴的详细信息
选项。

来自

I'd say that using Rails.logger.info is the way to go.

You won't be able to see it in the server console because it won't run via the server. Just open up a new console and tail -f the log file, it'll do the trick.

Many users are aware of the UNIX®
command 'tail', which can be used to
display the last few lines of a large
file. This can be useful for viewing
log files, etc.

Even more useful in some situations,
is the '-f' parameter to the 'tail'
command. This causes tail to 'follow'
the output of the file. Initially, the
response will be the same as for
'tail' on its own - the last few lines
of the file will be displayed.
However, the command does not return
to the prompt, and instead, continues
to 'follow' the file. When additional
lines are added to the file, they will
be displayed on the terminal. This is
very useful for watching log files, or
any other file which may be appended
over time. Type 'man tail' for more
details on this and other tail
options.

(via)

南街九尾狐 2024-08-28 23:17:16

在 Rails 2.X 中,将记录器重定向到模型中的 STDOUT:

ActiveRecord::Base.logger = Logger.new(STDOUT)

重定向控制器中的记录器:

ActionController::Base.logger = Logger.new(STDOUT)

In Rails 2.X to redirect the logger to STDOUT in models:

ActiveRecord::Base.logger = Logger.new(STDOUT)

To redirect logger in controllers:

ActionController::Base.logger = Logger.new(STDOUT)
絕版丫頭 2024-08-28 23:17:16

使用“&”执行后台作业并打开脚本/控制台或其他..
这样您就可以在同一窗口中运行多个命令。

tail -f log/development.log &
script/console
Loading development environment (Rails 2.3.5)
>> Product.all
2011-03-10 11:56:00 18062 DEBUG  Product Load (6.0ms)  SELECT * FROM "products"
[<Product.1>,<Product.2>]

注意 当有大量日志输出时,可能会很快变得马虎。

Execute a background job with '&' and open script/console or whatever..
That way you can run multiple commands in the same window.

tail -f log/development.log &
script/console
Loading development environment (Rails 2.3.5)
>> Product.all
2011-03-10 11:56:00 18062 DEBUG  Product Load (6.0ms)  SELECT * FROM "products"
[<Product.1>,<Product.2>]

note Can get sloppy quickly when there is a lot of logging output.

樱花坊 2024-08-28 23:17:16

创建一个应用程序助手来检测正在运行的环境并执行正确的操作怎么样?

def output_debug(info)
   if RAILS_ENV == "development"
      puts info
   else
      logger.info info
   end
end

然后调用output_debug而不是puts或logger.info

How about creating an application helper which detects which environment is running and does the right thing?

def output_debug(info)
   if RAILS_ENV == "development"
      puts info
   else
      logger.info info
   end
end

Then call output_debug instead of puts or logger.info

谎言 2024-08-28 23:17:16

扩展@Eric Duminil 的答案。我们可以使用rails提供的rake_tasks钩子仅在调用rake任务时运行代码块,即当服务器或控制台运行时该块不会运行。

# config/application.rb
module MyApp
  class Application < Rails::Application

    rake_tasks do
      config.after_initialize do
        Rails.logger.extend(
          ActiveSupport::Logger.broadcast(ActiveSupport::Logger.new(STDOUT))
        )
      end
    end
  end
end

输出:

cat lib/tasks/logger_test.rake

namespace :stdout_and_log do
  desc "Test if Rails.logger outputs to STDOUT and log file"
  task test: :environment do
    puts "HELLO FROM PUTS"
    Rails.logger.info "HELLO FROM LOGGER"
  end
end

❱ bundle exec rails stdout_and_log:test
HELLO FROM PUTS
HELLO FROM LOGGER

Extending on @Eric Duminil's answer. We can use use rake_tasks hook provided by rails to run code block only when rake tasks are invoked, i.e. this block will not run when server or console are run.

# config/application.rb
module MyApp
  class Application < Rails::Application

    rake_tasks do
      config.after_initialize do
        Rails.logger.extend(
          ActiveSupport::Logger.broadcast(ActiveSupport::Logger.new(STDOUT))
        )
      end
    end
  end
end

Output:

cat lib/tasks/logger_test.rake

namespace :stdout_and_log do
  desc "Test if Rails.logger outputs to STDOUT and log file"
  task test: :environment do
    puts "HELLO FROM PUTS"
    Rails.logger.info "HELLO FROM LOGGER"
  end
end

❱ bundle exec rails stdout_and_log:test
HELLO FROM PUTS
HELLO FROM LOGGER

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文