[英]Python logging & 3rd party modules
I'm struggling to get Python to log the way I want.我正在努力让 Python 以我想要的方式记录。 I've added some context to my log statements by adding a filter and updating the format string to print what's in the filter.我通过添加过滤器并更新格式字符串以打印过滤器中的内容,为我的日志语句添加了一些上下文。 That works as expected as long as all the code is mine.只要所有代码都是我的,它就可以按预期工作。
But if a 3rd party module logs something, it throws an error because that module doesn't know about my filter.但是,如果第 3 方模块记录了某些内容,则会引发错误,因为该模块不知道我的过滤器。
How do I get context into my logs without blowing up 3rd party module logging?如何在不破坏 3rd 方模块日志记录的情况下将上下文添加到我的日志中?
This code works fine in my modules.这段代码在我的模块中运行良好。 But if a 3rd party module wants to log something, they don't know about my ContextFilter, which details the nstid I want in my log messages.但是,如果第 3 方模块想要记录某些内容,他们不知道我的 ContextFilter,它详细说明了我在日志消息中想要的nstid 。
import logging
import sys
import boto3
from ContextFilter import ContextFilter
logging.basicConfig(
format='%(asctime)s %(levelname)-8s nstid:%(nstid)8s %(message)s',
handlers=[logging.StreamHandler(sys.stdout)],
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S'
)
log = logging.getLogger(__name__)
log.addFilter(ContextFilter())
log.info("important information")
I was able to get what I needed using a CustomAdapter instead of a ContextFilter, but I'm still interested in other solutions:我能够使用 CustomAdapter 而不是 ContextFilter 来获得所需的东西,但我仍然对其他解决方案感兴趣:
CustomAdapter.py:自定义适配器.py:
import logging
import os
class CustomAdapter(logging.LoggerAdapter):
def process(self, msg, kwargs):
nstid = os.environ['NSTID'] if 'NSTID' in os.environ else None
return '[NSTID: %s] %s' % (nstid, msg), kwargs
import logging
import os
import sys
import boto3
from CustomAdapter import CustomAdapter
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
handlers=[logging.StreamHandler(sys.stdout)],
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S'
)
log = CustomAdapter(logging.getLogger(__name__), {})
log.info("important information")
sqs = boto3.resource('sqs', region_name=os.environ['AWS_REGION'])
outputs:输出:
2020-04-13 13:24:38 INFO [NSTID: 24533] important information
2020-04-13 13:24:38 INFO Found credentials in shared credentials file: ~/.aws/credentials
the first line is from my code, the second from boto3第一行来自我的代码,第二行来自 boto3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.