Best way to add logger for ActiveResource

819 views Asked by At

What is the best way to add a logger for all the ActiveResource in rails?

In my application i have some methods which call the API through ActiveResource which sometimes gives TimeOut error.

So, i just want to log the url, method(get/post) and some url related stuff in logger for which it gives the TimeOut or any other Error.

3

There are 3 answers

3
Paulo Fidalgo On

You can define a new logger for ActiveResource by adding this to your config/environment.rb:

 logger = Logger.new('log/active_resource.log', 'daily');·
 logger.level = Rails.env.dev? ? Logger::DEBUG : Logger::INFO;·
 ActiveResource::Base.logger = logger

If you just want to log the errors you can use it only for Logger::Error:

 logger = Logger.new('log/active_resource.log', 'daily');·
 logger.level = Logger::Error
 ActiveResource::Base.logger = logger

To have a custom exception handling I will recommend to copy the source file of ActiveResource Exception handling to config/initializers/ and change the file according to your needs. This way you are controlling the behaviour of your exceptions and since there are different type of exceptions you'll be able to customize all of them.

2
Siva On

How to add logger for ActiveResource in rails ?

Instantiate a new logger for ActiveResource

 ## config/environment.rb

 logger = Logger.new('log/active_resource.log')
 logger.level = Logger::DEBUG 
 ActiveResource::Base.logger = logger

I need to add some custom message

Override the exception handlers of ActiveResource with yours. Checkout the source

Monkey-patch the library functions like below

 ## create config/initializers/active_resource_patch.rb

 module ActiveResource
   class TimeoutError
     def to_s
      @message + " my custom message"
     end
   end
 end

I have modified the time out error to display with a custom message.

0
floum On

Not sure of which type of custom message you are trying to add. Maybe you can go for Logger Inheritance :

class CustomLogger < Logger
  def self.error(message)
    super(message  + ' my custom message')
  end
end

#added code from Paulo Fidalgo
logger = CustomLogger.new('log_location', 'daily')
logger.level = Logger::ERROR
ActiveResource::Base.logger = logger