'thread._local'对象没有属性 [英] 'thread._local' object has no attribute
问题描述
我试图通过添加上下文过滤器来更改日志记录格式.我的格式是这样的
I was trying to change the logging format by adding a context filter. My Format is like this
FORMAT = "%(asctime)s %(VAL)s %(message)s"
这是我用来设置VAL格式的类.
This is the class I use to set the VAL in the format.
class TEST:
def __init__(self, val):
self.test_var=threading.local()
self.test_var.value=val
def filter(self,record):
record.VAL=self.test_var.value
return True
def setValue(self,val)
self.test_var.value=CMDID
它在单线程环境中可以正常工作,但是对于某些多线程环境,我会收到错误消息
It works fine in a single threaded environment, but for a certain multi-threaded environment I get the error
<Fault 1: "exceptions.AttributeError:'thread._local' object has no attribute 'value'">
有人可以告诉我这是怎么回事吗?以及如何纠正?
Can anyone tell me what's wrong here ?? and how to rectify?
推荐答案
好吧,例外是告诉您,从threading.local()
返回的thread._local
对象没有可分配val
的value
属性. >至.您可以通过在self.test_var=threading.local()
行之后添加dir(self.test_var)
来确认.那对我来说就是这样:
Well, the exception is telling you that the thread._local
object returned from threading.local()
doesn't have a value
attribute that you can assign val
to. You can confirm that by adding a dir(self.test_var)
after the self.test_var=threading.local()
line. That returns this for me:
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__',
'__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__str__']
实际上,help(threading.local())
将向您显示确实存在的方法和属性-value
不在其中.
Indeed, help(threading.local())
will show you the methods and attributes that do exist - value
is not among them.
如果您尝试添加新属性,那么您可能想要:
If you are attempting to add a new attribute, then perhaps you want:
self.test_var.__setattr__('value',val)
这实际上将创建属性并为其分配值.
This will actually create the attribute and assign the value to it.
通常不简单地通过分配实例属性来创建实例属性,就像非实例变量是...
Instance attributes are not generally created simply by assigning to them, like non-instance variables are...
这篇关于'thread._local'对象没有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!