我在lib/tasks 中制作了taks 文件
任务文件总是在项目日志目录下记录文件
而且我知道哪里出现了错误行
现在记录行自定义文本“line N occurred”
下面是我的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
如何获取行号并记录这些信息?
最佳答案
你不应该以这种方式创建记录器,有 Ruby Logger专门为此上课。它提供了很好的特性,比如允许你用不同方法记录消息的级别,你只需要改变记录器的级别来隐藏一些消息。例如,作为开发人员,您需要一些消息来调试应用程序,但您不希望这些消息出现在生产版本中。因此,当您在开发过程中,您创建了级别 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
关于ruby-on-rails - Rails 4,如何使用行号记录文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28668124/