我目前正在一个项目中使用一个单一的根记录程序。我从阅读日志中了解到这是一件坏事,但我正在努力寻找一个好的解决方案来实现它给我们带来的好处。在
我们所做的事情(部分是为了避免使用不同的记录器,但在一定程度上给了我们一个很好的特性)就是使用一个log_prefix
装饰器。在
例如
@log_prefix("Download")
def download_file():
logging.info("Downloading file..")
connection = get_connection("127.0.0.1")
//Do other stuff
return file
@log_prefix("GetConnection")
def get_connection(url):
logging.info("Making connection")
//Do other stuff
logging.info("Finished making connection")
return connection
这为我们提供了一些很好的格式化日志,如下所示:
^{pr2}$这也意味着如果我们
@log_prefix("StartTelnetSession")
logging.info("Starting telnet session..")
connection = get_connection("127.0.0.1")
我们在末尾得到相同的前缀:
StartTelnetSession:Starting telnet session..
StartTelnetSession:GetConnection:Making Connection
StartTelnetSession:GetConnection:Other stuff
StartTelnetSession:GetConnection:Finished making connection
事实证明,这对开发和支持非常有用。在
我可以看到很多情况下,实际上只使用一个单独的记录器来执行操作可以解决我们的问题,但我也可以看到一些情况,即放弃我们的嵌套将使事情变得更糟。在
有没有什么模式或常见的用途来嵌套伐木工人?i、 e
logging.getLogger("Download").getLogger("MakingConnection")
还是我在这里遗漏了什么?在
这里有一个替代方法,它使用logging.Filter来修改
record.msg
。通过修改消息而不是添加%(prefix)s
字段, 格式不需要更改。在{cd3>哪个伐木工人能更容易地使用它
要获取前缀,应使用调用
add_prefix_filter
初始化记录器:要将标签附加到前缀,函数应该像以前一样用
@log_prefix(label)
修饰。在实用工具_日志记录.py公司名称:
^{pr2}$在主.py公司名称:
^{3}$在棒.py公司名称:
收益率
日志名称是分层的。在
此记录器将从
logging.getLogger("Download")
继承任何配置Python2.7还添加了一个方便的函数,用于访问任意记录器的后代。在
^{pr2}$您可以使用LoggerAdapter添加额外的上下文信息:
实用工具_日志记录.py公司名称:
在食品公司名称:
^{pr2}$在棒.py公司名称:
^{3}$收益率
注意:我不认为为每一个都有一个新的记录器实例是个好主意 前缀是因为these instances are not garbage collected。全部 您需要使某个
prefix
变量具有不同的值,具体取决于 上下文。你不需要一个新的Logger实例 去吧。在相关问题 更多 >
编程相关推荐