I recently discovered structlog
and want to use it to log the object attributes of some objects.
I'm unsure about two things:
1) What's the best practice for object-oriented logging? I want to bind some object attributes, eg, ID, that are always logged for an object. The only example with objects I can find is this one, where logger
is created as global variable and each object creates a new logger and again the functions too. (If I understand correctly.)
2) What if some of my attributes change over time, eg, the position of a user? If I just bind the position in the constructor, it always logs the same position even when the user moves. Do I have to "rebind" after each movement? How?
This is what I currently have:
import structlog
logger = structlog.get_logger()
class User:
def __init__(self, id, pos):
self.id = id
self.pos = pos
self._log = logger.bind(id=self.id, pos=str(self.pos))
def move(self, delta):
log = self._log.bind(delta=delta)
self.pos += delta
log.msg("User moved")
Am I using structlog
correctly/well in this object-oriented example? Anyway, this always prints the same position even when the user moves. I guess, I have to do log.msg("User moved", pos=str(self.pos))
to update the context? But that would only update the context for the logger within the function. In other functions, the position would still be logged wrongly.