Optimise LoggingContext creation and copying

It turns out that the only thing we use the __dict__ of LoggingContext for is
`request`, and given we create lots of LoggingContexts and then copy them every
time we do a db transaction or log line, using the __dict__ seems a bit
redundant. Let's try to optimise things by making the request attribute
explicit.
This commit is contained in:
Richard van der Hoff 2018-01-11 22:40:51 +00:00
parent febdca4b37
commit 44a498418c
3 changed files with 33 additions and 22 deletions

View file

@ -52,13 +52,16 @@ except Exception:
class LoggingContext(object):
"""Additional context for log formatting. Contexts are scoped within a
"with" block.
Args:
name (str): Name for the context for debugging.
"""
__slots__ = [
"previous_context", "name", "usage_start", "usage_end", "main_thread",
"__dict__", "tag", "alive",
"previous_context", "name", "ru_stime", "ru_utime",
"db_txn_count", "db_txn_duration", "usage_start", "usage_end",
"main_thread", "alive",
"request", "tag",
]
thread_local = threading.local()
@ -96,7 +99,9 @@ class LoggingContext(object):
self.db_txn_count = 0
self.db_txn_duration = 0.
self.usage_start = None
self.usage_end = None
self.main_thread = threading.current_thread()
self.request = None
self.tag = ""
self.alive = True
@ -105,7 +110,11 @@ class LoggingContext(object):
@classmethod
def current_context(cls):
"""Get the current logging context from thread local storage"""
"""Get the current logging context from thread local storage
Returns:
LoggingContext: the current logging context
"""
return getattr(cls.thread_local, "current_context", cls.sentinel)
@classmethod
@ -155,11 +164,13 @@ class LoggingContext(object):
self.alive = False
def copy_to(self, record):
"""Copy fields from this context to the record"""
for key, value in self.__dict__.items():
setattr(record, key, value)
"""Copy logging fields from this context to a log record or
another LoggingContext
"""
record.ru_utime, record.ru_stime = self.get_resource_usage()
# 'request' is the only field we currently use in the logger, so that's
# all we need to copy
record.request = self.request
def start(self):
if threading.current_thread() is not self.main_thread: