简体   繁体   中英

Use structlog to log changing object attributes

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.

I personally tend to only log out IDs but if you want more rich log lines, you can bind the whole object to the logger and write a simple processor that extracts the interesting attributes for you:

def user_extractor(_, __, ed):
    user = ed.pop("user", None)
    if user is not None:
        ed.update(user_id=user.id, user_pos=user.pos)

    return ed

A more general option could be to define serialization using functools.singledispatch and write a processor that uses it (shouldn't be more than a few lines either). I think we'll add support for that to structlog proper too, sooner or later.


See http://www.structlog.org/en/stable/processors.html for more details on writing processors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM