Is Ruby's stdlib Logger class thread-safe?

后端 未结 4 691
长情又很酷
长情又很酷 2021-01-03 18:31

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 fe

相关标签:
4条回答
  • 2021-01-03 18:57

    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 :-)

    0 讨论(0)
  • 2021-01-03 18:57

    Below is my original response, which is actually wrong. Read Nemo157's comment below. I left it here for reference only.

    Original:

    I don't think it matters. All implementations of Ruby that I know of so far effectively run one thread at a time anyway: It does allow you to start many threads, but only one thread runs at a time per process.

    0 讨论(0)
  • 2021-01-03 18:57

    source

    Try if logs will be mixtures in multithreads

    require 'logger'
    require 'parallel'
    
    logger = Logger.new("/tmp/test.log")
    
    Parallel.map(['a','b'], :in_threads => 2) do |letter|
      1000.times do
        logger.info letter * 5000
      end
    end
    

    Testing the log file

    egrep -e 'ab' -e 'ba' /tmp/test.log
    [empty]
    

    The reason why logs didn't get mixtured:

    def write(message)
      @mutex.synchronize do
        ...    
        @dev.write(message)        
      end
    end
    
    0 讨论(0)
  • 2021-01-03 19:01

    Some Ruby classes are designed to be thread safe, but don't explicitly say so in words of one syllable in their documentation. Unlike documentation in other programming languages such as PHP.

    I remember being asked whether Queue was thread-safe on Stack Overflow, and even though it was, the documentation didn't spell that out.

    0 讨论(0)
提交回复
热议问题