0

I am getting logging messages twice in my Django application: First with formatting and second without any formatting i.e. only message.

2021-09-30 21:28:14,948 - dirB.my_module - INFO - Initialized Query Engine: 0.6080608367919922 seconds
Initialized Query Engine: 0.6080608367919922 seconds

I have a module which looks similar to the auxiliary module mentioned in https://docs.python.org/3/howto/logging-cookbook.html#using-logging-in-multiple-modules

My module_logger adds console handler which has the formatter as shown in main module in the above URL.

To avoid repeat of log message, I following the suggestion mentioned in https://stackoverflow.com/a/6729713/282155 i.e. adding console handler only if logger has no handlers associated with it.

But still facing the same error.

Though my final intention is to have multiple module logging, but for debugging the above mentioned bug, I am currently having the logger in module_logger only.

Here's how I have created module_logger

module_logger = logging.getLogger("{}".format(__name__))
logging_level = os.environ.get("LOGLEVEL", "WARNING")
module_logger.setLevel(level=logging_level)
if not module_logger.handlers:
    console_handler = logging.StreamHandler()
    console_handler.setLevel(level=logging_level)
    formatter = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    console_handler.setFormatter(fmt=formatter)
    logger.addHandler(hdlr=console_handler)

Here's the relevant directory structure:

  • dirA

    • views.py
  • dirB

    • my_module.py

views.py

def view1(request):
    // Calls some_function() of my_module

my_module.py

Similar to auxiliary module shown in Logging cookbook (as mentioned in above url).

Kaushik Acharya
  • 1,308
  • 2
  • 14
  • 24
  • **Issue Solved**: Turning off **propagate** solved the problem. **logger.propagate = False** as suggested in https://stackoverflow.com/a/21127526/282155 – Kaushik Acharya Oct 01 '21 at 10:17

0 Answers0