【问题标题】:Rails 4, How to log file with line NumberRails 4,如何使用行号记录文件
【发布时间】:2023-03-07 06:07:02
【问题描述】:

我在 lib/tasks 制作了 taks 文件

并且任务文件总是在项目日志目录中记录文件

我知道错误行发生在哪里

现在记录行自定义文本“第 N 行发生了”

下面是我的tasks.rb文件

17       log_file = File.open("#{Rails.root}/log/log_file.log", "w")
18 
19     begin
20       number_of_row = 8000
21       process_page = args[:page].to_i
22 
23       conn_url = CONNECTION_URL
24       xml_page = Nokogiri::XML(open(conn_url))
25       
26       root = xml_page.css("root")      
27       if root.css("code").text != "0000" 
28
29
30 
31         log_file.write "\n\n-------------------------------"
32         log_file.write "Line 32 ---------------------------\n\n"
33         log_file.write "Parse Error : #{conn_url},\n code :  #{root.css("code").text}, \n msg: #{root.css("message").text} "
34         log_file.write "\n\n-------------------------------\n\n"
35       end
36     rescue => e
37       log_file.write "Line 37 ---------------------------\n\n"
38   log_file.write "Line 37 ---------------------------\n\n"
39     end

如何获取行号并记录这些信息?

【问题讨论】:

  • 你可以使用__LINE__ - stackoverflow.com/questions/12175793/…
  • @Lesleh Thx :) 效果很好
  • 把这个放到文件t.rb:def my_method; puts "line #{__LINE__} in file #{__FILE__}, in method '#{__method__}'"; end; my_method。然后Ruby 't.rb' => line 2 in file t.rb, in method 'my_method'.

标签: ruby-on-rails ruby ruby-on-rails-4 logging


【解决方案1】:

您不应该以这种方式创建记录器,Ruby Logger 专门用于此类。它提供了很好的功能,比如 level 可以让你用不同的方法记录消息,你只需要改变 logger 的 level 来隐藏一些消息。例如,作为开发人员,您需要一些要调试应用程序的消息,但您不希望这些消息出现在生产版本中。因此,当您在开发中时,您创建级别 Logger::DEBUG,并使用 debug 方法记录这些消息,当您将应用程序投入生产时,您只需将 Logger 级别更改为 Logger::INFO,它不会写入使用debug 方法添加的消息。

   log_file = Logger.new("#{Rails.root}/log/log_file.log", "w")
   log_file.level = Logger::INFO # this will print the messages added with info, fatal, warn, error and unknown methods
   # but will hide those added with the debug method
   begin
     number_of_row = 8000
     process_page = args[:page].to_i
     conn_url = CONNECTION_URL
     xml_page = Nokogiri::XML(open(conn_url)) 

     root = xml_page.css("root")      
     if root.css("code").text != "0000" 
        log_file.info "#{__LINE__} #{'-' * 30}"
        log_file.info "Parse Error : #{conn_url},\n code :  #{root.css("code").text}, \n msg: #{root.css("message").text} "
        log_file.info "-" * 30
     end
   rescue => e
     log_file.fatal "#{__LINE__} #{'-' * 30}\n\n"
   end

【讨论】:

  • thx :),我忘记使用 Logger Class,我将 File 替换为 Logger Class
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多