Is Ruby's stdlib Logger class thread-safe?

后端 未结 4 724
长情又很酷
长情又很酷 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

    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
    

提交回复
热议问题