2011-11-23 218 views
2

我有这样的:组红宝石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类。在实时并行运行线程的同时,在每个线程的基础上设置程序名。

回答

13

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

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'