[英]Rails 4, How to log file with line Number
我在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
如何獲取行號並記錄這些信息?
您不應該以這種方式創建記錄器,有專門用於此的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.