Saturday, 23 September 2023

django print will causing http request not returning causing 500 error, use logging.info instead

 django 

print is bascially like echo, it will instruct the server to write output then browser treat as a response unable to be handleded (500)

return HttpResponse() wont exetue due to stderr basically like stdout behaviour


soluntion 

replace print with logger instead :


https://stackoverflow.com/questions/22134895/django-logging-to-console


In settings.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'app_api': {
            'handlers': ['console'],
            'level': 'INFO',
        },
    },
    }

Somewhere in your application views

import logging
logger = logging.getLogger('app_api') #from LOGGING.loggers in settings.py

try:
    one = 1/0
except Exception as e:
    logger.error(e)

No comments:

Post a Comment