<p>您可以使用<a href="https://docs.python.org/2/library/logging.html#loggeradapter-objects" rel="nofollow">LoggerAdapter</a>添加额外的上下文信息:</p>
<p>实用工具_日志记录.py公司名称:</p>
<pre><code>import functools
def log_prefix(logger, label, prefix=list()):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
prefix.append(label)
logger.extra['prefix'] = ':'.join(prefix)
result = func(*args, **kwargs)
prefix.pop()
logger.extra['prefix'] = ':'.join(prefix)
return result
return wrapper
return decorator
</code></pre>
<p>在食品公司名称:</p>
^{pr2}$
<p>在棒.py公司名称:</p>
^{3}$
<p>收益率</p>
<pre><code>Download __main__ INFO Downloading file..
Download:GetConnection bar INFO Making connection
Download:GetConnection bar INFO Finished making connection
GetConnection bar INFO Making connection
GetConnection bar INFO Finished making connection
</code></pre>
<p>注意:我不认为为每一个都有一个新的记录器实例是个好主意
前缀是因为<a href="https://docs.python.org/2/howto/logging-cookbook.html#adding-contextual-information-to-your-logging-output" rel="nofollow">these instances are not garbage
collected</a>。全部
您需要使某个<code>prefix</code>变量具有不同的值,具体取决于
上下文。你不需要一个新的Logger实例
去吧。在</p>