So I have a several of django settings files, one for testing, others for different customers.
None of these settings files change sys.path
at all.
All of them include a singular base settings file that contains INSTALLED_APPS
.
Most of the files have code that does this:
import logging
logger = logging.getLogger(__name__)
logger.error("Something went wrong")
In my test settings files, the module __name__
looks like saml.xyz
so the logger.name is saml.xyz
but when I use a different settings files, the module __name__
looks like apps.saml.xyz
which makes the logger.name apps.saml.xyz
.
This causes some log messages to be missed because the handler is connected to the wrong place. A handler for saml.xyz
will not get messages for apps.saml.xyz
and vice versa. All the routing is based on the configured logger/handler including the apps. portion or not.
So how does python decide which __name__
to give a file, and how could my different settings files affect that __name__
without changing sys.path?
The commands are otherwise identical:
python manage.py test --settings=projectname.test saml
which yields
>>> logger.name
'saml.xyz'
or
python manage.py test --settings=projectname.customer saml
which yields
>>> logger.name
'apps.saml.xyz'
__name__
is the name under which the current module was imported.
If the module was imported with import saml.xyz
, __name__
reflects that directly. If you sometimes see apps.saml.xyz
then your module was imported using that name, and there are two copies of your module loaded in memory; Python sees the two as separate.
You should avoid importing nested modules; use only the top-level name. Stick to either apps.saml.xyz
or saml.xyz
, but if the latter must be used, make sure apps/
is not a package and is not itself listed on the python module search path sys.path
.
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.