在每个线程的基础上设置ruby logger.progname [英] set ruby logger.progname on per thread basis

查看:57
本文介绍了在每个线程的基础上设置ruby logger.progname的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

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

上面的代码通过设置progname可以正确地识别用户的不同线程,但是问题是我必须使用Mutex类进行同步,因此失去了并行计算,因为我必须等待请求被发送如果我想在日志中获取正确的程序名,则在继续操作之前收到该消息.

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.

是否有一种无需使用Mutex类即可执行此操作的方法.实时并行运行线程时,请在每个线程的基础上设置progname.

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.

推荐答案

我终于找到了答案.您定义线程局部变量,然后修改日志格式化程序以在记录日志时将其包括在内.这是修改格式化程序的代码.

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

在每个线程中,您将添加如下内容: Thread.current['id'] = 'whatever'

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

这篇关于在每个线程的基础上设置ruby logger.progname的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆