Delgan / loguru

Python logging made (stupidly) simple
MIT License
19.98k stars 699 forks source link

Weird behaviour of logger after 'bind' #1191

Open argrento opened 2 months ago

argrento commented 2 months ago

Consider this code


import sys

from loguru import logger

print(f"foo module {logger=}")

class Foo:
    def __init__(self):
        l = logger.bind(source="foo")
        l.remove()
        l.add(sys.stderr)
        print(f"foo __init__ {logger=}, {l=}")

if __name__ == "__main__":
    f = Foo()

When I print it, I see the following:

foo module logger=<loguru.logger handlers=[(id=0, level=10, sink=<stderr>)]>
foo __init__ logger=<loguru.logger handlers=[(id=1, level=10, sink=<stderr>)]>, l=<loguru.logger handlers=[(id=1, level=10, sink=<stderr>)]>

Why id of logger also changed?

Delgan commented 1 month ago

Keep in mind there is only one global registry of the handlers. The logger is a facade toward these handlers. The bind() method is helpful to give context to messages logged by a logger. However, in the end, it will always end up to the same set of handlers, because they share the same reference to it.

If you really want to create separate logger that can manage handlers independently, refer to the documentation: Creating independent loggers with separate set of handlers.