user3556757
user3556757

Reputation: 3609

Django settings module...not possible to run the logger?

I use the python logging module in my my_app/views.py file with no problem.

I tried to use it inside the staging_settings.py that I use for my configuration. But the messages never reach the error log, whilst the messages from the views.py work fine.

my staging_settings.py:

LOGGING= { ..redacted for space.. } # the logging config-dict 

import logging
logger = logging.getLogger(__name__)
logger.debug(F"this is staging_ setup")

Is it just an impossibility to run a logger inside a setup.py? I guess the server actually isn't running yet, so there is nothing for the logger to send to? I'm running this on pythonanywhere, so I don't really have a console to simply print() to or some other hack alternative.

Upvotes: 0

Views: 119

Answers (1)

Vinay Sajip
Vinay Sajip

Reputation: 99317

Logging isn't configured at the time the settings file is imported, so you can't do logging from the module level in it. The sequence is

  1. Django imports the settings from your staging_settings.py
  2. Django fetches the LOGGING dict with the configuration from that imported module
  3. Django configures logging with the configuration
  4. When you log anything after that, logging then starts to output stuff as per your configuration

You can't expect to log and get log output in step 1.

Update: AFAIK there's no Django-version-independent way of determining when logging has been configured. You could define your own filter which sets a flag when instantiated, which would happen during configuration. Anyway, that doesn't help you if you need to log from the settings module in module-level code. However, functions that are defined in the settings module and are called later (after logging configuration has happened) can do logging.

Upvotes: 1

Related Questions