How to write / clear Rails log at process termination

The Rails logger has an auto_flushing method. This delays logging until the number of entries is the same as everything that was set. This has been around with Rails 2 and is designed to speed things up by stopping persistent writing to disk at boot time.

This is great in most cases, but we have short work tasks that never last long enough to get past the flash - all errors disappear.

Is there a way to ensure that the log is cleared when the process dies?

EDIT

In the end I did it (but it is very verbose)

af = Rails.logger.auto_flushing Rails.logger.auto_flushing = true Rails.logger.error "my message" Rails.logger.auto_flushing = af 

This causes the message to exit, but after that it automatically shuts down.

For a truly complete solution, put this in the initializer:

 class << Rails.logger def flush_error( message ) Rails.logger.error message Rails.logger.flush end end 

Then just use the method as and when ...

+4
source share
4 answers

If for some reason the rails do not start the at_exit hook (flying monkeys are hiding with your sanity) and you really want these log entries, do as some people say, and run them after important logging protocols:

 Rails.logger.flush 

or

 logger.flush 

Voila.

+4
source

Can you set it to "1" and it will be cleared after each message?

 config.logger.auto_flushing = 1 

[ EDIT : as madlep points out in the comment above - this will be the full hog resource and probably not the best way to log in general. But if you are hunting for bugs - this is the way to find it. This and switching your log to the "debug level"]

You can also disable it with:

 config.logger.auto_flushing = false 

But it just means you need to manually clean ...

alternatively, you can specifically clear the log at the end of each of your scripts with

 Rails.logger.flush 
+3
source

Try something like

 Signal.trap("EXIT") { Rails.logger.flush } 

When you initialize the registration to register the signal handler with the process. When he dies, he will do everything in the block before completing

Read more about docs for more information.

(A note is a completely untested code with a rail logger, but it generally works just to do something when the process dies.

+2
source

In Rails 3.1, this is no longer necessary: โ€‹โ€‹The code in the Railties / bootstrap.rb application now includes at_exit to clear the log.

Enjoy.

+1
source

All Articles