在Django,我到处都有记录器,目前有硬编码的名字.
对于模块级日志记录(即,在视图函数模块中),我有这样做的冲动.
log = logging.getLogger(__name__)
Run Code Online (Sandbox Code Playgroud)
对于类级别的日志记录(即,在类__init__方法中),我有这样做的冲动.
self.log = logging.getLogger("%s.%s" % (
self.__module__, self.__class__.__name__))
Run Code Online (Sandbox Code Playgroud)
在我解决几十次事件之前,我正在寻找第二意见getLogger("hard.coded.name").
这会有用吗?还有其他人用同样缺乏想象力的方式命名他们的记录器吗?
此外,我应该分解并为此日志定义编写类装饰器吗?
好的,首先检查以下代码:
class DemoClass():
def __init__(self):
#### I really want to know if self.Counter is thread-safe.
self.Counter = 0
def Increase(self):
self.Counter = self.Counter + 1
def Decrease(self):
self.Counter = self.Counter - 1
def DoThis(self):
while True:
Do something
if A happens:
self.Increase()
else:
self.Decrease()
time.sleep(randomSecs)
def DoThat(self):
while True:
Do other things
if B happens:
self.Increase()
else:
self.Decrease()
time.sleep(randomSecs)
def ThreadSafeOrNot(self):
InterestingThreadA = threading.Thread(target = self.DoThis, args = ())
InterestingThreadA.start()
InterestingThreadB = threading.Thread(target = self.DoThat, args = ())
InterestingThreadB.start()
Run Code Online (Sandbox Code Playgroud)
我面临着和上面相同的情况.我真的想知道它是否是线程安全的 …
我找到了一种优雅的方法来装饰Python类来实现它singleton.该类只能生成一个对象.每次Instance()调用都返回相同的对象:
class Singleton:
"""
A non-thread-safe helper class to ease implementing singletons.
This should be used as a decorator -- not a metaclass -- to the
class that should be a singleton.
The decorated class can define one `__init__` function that
takes only the `self` argument. Also, the decorated class cannot be
inherited from. Other than that, there are no restrictions that apply
to the decorated class.
To get the singleton instance, use the …Run Code Online (Sandbox Code Playgroud)