The official python logging documentation says this:
The name is potentially a period-separated hierarchical value, like foo.bar.baz (though it could also be just plain foo, for example). Loggers that are further down in the hierarchical list are children of loggers higher up in the list. For example, given a logger with a name of foo, loggers with names of foo.bar, foo.bar.baz, and foo.bam are all descendants of foo. The logger name hierarchy is analogous to the Python package hierarchy, and identical to it if you organise your loggers on a per-module basis using the recommended construction logging.getLogger(__name__). That’s because in a module, __name__ is the module’s name in the Python package namespace.
But I have found that last sentence not to be strictly true. The value of __name__
seems to depend on how a module is imported. The following demonstrates this:
Given two modules, foo and bar both in package pkg:
This is foo:
def showFoosName():
print __name__
and this is bar:
from pkg import foo
if __name__ == '__main__':
foo.showFoosName()
running bar produces
pkg.foo
However, if we introduce baz into package pkg, which imports foo simply as foo, which is legal because both are in the same package:
import foo
if __name__ == '__main__':
foo.showFoosName()
running baz produces
foo
Now bringing this discussion back to logging and logging configuration, it seems that the python logging recommendation of naming loggers with __name__
only holds good if imports within a package are coded with from pkg import bar
syntax. This is not what I would have expected. I would have thought that __name__
's value would be independent of how it was imported.