Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Ruby's stdlib Logger class thread-safe?

In short, is the standard library Logger class in Ruby thread-safe? Only useful info Google turned up was someone on a forum saying it "seems" thread-safe. And I don't feel like spending time testing a logger to try to figure out if it is or not.

For the time being I'm using log4r which is thread-safe, but it's overkill if the standard library already does it.

like image 844
jimeh Avatar asked Jan 11 '11 16:01

jimeh


People also ask

Are Ruby hashes thread safe?

No, you cannot rely on Hashes being thread safe, because they aren't built to be thread safe, most probably for performance reasons. In order to overcome these limitations of the standard library, Gems have been created which provide thread safe (thread_safe) or immutable (hamster) data structures.

Does Ruby use threads?

Ruby makes it easy to write multi-threaded programs with the Thread class. Ruby threads are a lightweight and efficient way to achieve concurrency in your code.

What is thread in Ruby?

Threads are the Ruby implementation for a concurrent programming model. Programs that require multiple threads of execution are a perfect candidate for Ruby's Thread class. For example, we can create a new thread separate from the main thread's execution using ::new . thr = Thread.


1 Answers

A quick look at logger.rb reveals code such as the following:

def write(message)   @mutex.synchronize do     if @shift_age and @dev.respond_to?(:stat)       begin         check_shift_log       rescue         raise Logger::ShiftingError.new("Shifting failed. #{$!}")       end     end     @dev.write(message)   end end 

So while I can't vouch for whether it gets thread-safety correct, I can confirm that it is making a concerted effort to do it right!

P.S. It's often easy to answer questions like this for yourself by reading the code :-)

like image 121
Avdi Avatar answered Sep 21 '22 09:09

Avdi