Skip to content

Instantly share code, notes, and snippets.

@benweint
Last active December 10, 2015 02:48
Show Gist options
  • Save benweint/4370423 to your computer and use it in GitHub Desktop.
Save benweint/4370423 to your computer and use it in GitHub Desktop.
Ruby Logger multi-process concurrency test
#!/usr/bin/env ruby
# Ruby Logger multi-process concurrency test.
# In an attempt to answer my own question at:
# http://stackoverflow.com/questions/13908745/can-rubys-stdlib-logger-class-safely-handle-writers-from-multiple-proceses
#
# Every line in each log file should begin with 'W,', and this string should
# appear in no other places in each line. To check results:
#
# grep -l '.W,' *.log
#
# Any files appearing as a result of this search have log lines that are mixed
# in with each other.
require 'logger'
nprocs = 8
line_length = 160
nlines = 10000
f_synconly = File.open("test.synconly.log", "w"); f_synconly.sync = true
f_wronly = open("test.wronly.log", (File::WRONLY | File::APPEND | File::CREAT))
f_all = open("test.all.log", (File::WRONLY | File::APPEND | File::CREAT)); f_all.sync = true
loggers = [
Logger.new("test.default.log"),
Logger.new(f_synconly),
Logger.new(f_wronly),
Logger.new(f_all)
]
puts "Spawning #{nprocs} children"
(1..nprocs).each do |procid|
pid = Process.fork
if !pid # in child
nlines.times do
msg = ("P#{$$}" * line_length)
loggers.each { |l| l.warn(msg) }
end
loggers.each { |l| l.close }
exit
end
end
puts "Waiting on children"
Process.wait
puts "Done"; $stdout.flush
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment