在每个线程的基础上设置 ruby​​ logger.progname

发布于 2024-12-17 20:23:33 字数 863 浏览 1 评论 0原文

我有这样的:

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 类来同步它,从而失去并行计算,因为我必须等待请求如果我想在日志中获取正确的程序名,请在继续之前发送和接收。

有没有办法在不使用 Mutex 类的情况下做到这一点。在实时并行运行线程时,在每个线程的基础上设置程序名。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一场信仰旅途 2024-12-24 20:23:33

我终于找到了答案。您定义一个线程局部变量,并修改日志格式化程序以在记录时包含它。这是修改格式化程序的代码。

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

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

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'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文