set ruby logger.progname on per thread basis

我们两清 提交于 2019-12-06 11:04:29

问题


I have this :

class Stress
  def initialize(user, pass)
    @user = user
    @pass = pass
    @agent = Mechanize.new do |a|
      a.user_agent_alias = 'Windows Mozilla'
      a.history.max_size = 0
      a.log = my_log
      a.log.progname = @user
    end
  end
  def browse
  @agent.log.progname = @user
  # open/close page
  end
end

my_log = Logger.new('dump.log')
my_log.level = Logger::DEBUG
atom = Mutex.new

for i in (Attempts_start..Attempts_end)
  threads << Thread.new(Creden_base + i.to_s) do |user|
    stress = Stress.new(user, user)
    for j in (0..Attempts_req) do
        atom.synchronize {stress.browse} # has to be atomic
    end
  end
end

The above code correctly identifies the different threads by the user by setting the progname, but the problem is I have to use the Mutex class to synchronize it, thus loosing the parallel computing since I have to wait for the request to be sent and received before continuing if I want to get the correct progname in the logs.

Is there a way to do this without using the Mutex class. Have the progname set on a per thread basis while running the threads in real-time parallel.


回答1:


I have finally found my answer. You define a thread local variable and you modify the log formatter to include it when logging. Here is the code to modify the formatter.

  Log.formatter = proc do |severity, datetime, progname, msg|
    "#{severity} [#{Time.now.strftime('%H:%M:%S')}] #{Thread.current['id']} --> #{msg}\n"
  end

And in each thread you would add something like this : Thread.current['id'] = 'whatever'



来源:https://stackoverflow.com/questions/8249243/set-ruby-logger-progname-on-per-thread-basis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!