Rails 4, How to log file with line Number

logging, ruby, ruby-on-rails, ruby-on-rails-4

Solution

You should not create a logger this way, there is the Ruby Logger class specifically for this. It provides good features, like level which will allow you to log messages with different methods, and you just need to change the level of the logger to hide some messages. For example, as a developer you need some messages that you want to debug the app, but you don't want those messages to appear in the production version. So while you're in development you make the level `Logger::DEBUG`, and use `debug` method to log those messages, and when you put the app on production you just change the Logger level to Logger::INFO, which will not write messages added with the `debug` method.

   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

Problem

I made taks file at lib/tasks and task file always logging file at out project log directory and I know where occured error line now logging line custom text "line N occured" below is my tasks.rb file ``` 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 ``` How to get line number and log these info?

Original source

Related problems