Suppose I have this function in views.py
in Django.
def test_func(request, username):
print("print debug msg in test_func()")
# other code
return
Using print()
doesn't look like a good way to print out debug messages because the messages will be printed out even in production mode. How do I write debug messages on Django so that the messages will only be printed out in DEBUG mode?
I am using Django 4.1
EDIT: Since the question is closed, I will write my own answer here. Credit goes to https://www.containiq.com/post/django-logging This is what I did.
In settings.py
,
LOGGING_CONFIG = None
LOGLEVEL = os.environ.get('LOGLEVEL', 'info').upper()
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
# exact format is not important, this is the minimum information
'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
},
'django.server': DEFAULT_LOGGING['formatters']['django.server'],
},
'handlers': {
# console logs to stderr
'console': {
'class': 'logging.StreamHandler',
'formatter': 'default',
},
'django.server': DEFAULT_LOGGING['handlers']['django.server'],
},
'loggers': {
# default for all undefined Python modules
'': {
# 'level': 'WARNING',
'level': 'INFO',
'handlers': ['console'],
},
# Our application code
'app': {
'level': LOGLEVEL,
'handlers': ['console'],
# Avoid double logging because of root logger
'propagate': False,
},
# Default runserver request logging
'django.server': DEFAULT_LOGGING['loggers']['django.server'],
},
})
In views.py
,
import logging
logger = logging.getLogger(__name__)
# example to print out log msg.
# logger.info("debug_message")