2

I followed the django documentation and tried to use the logger.error to save the error into the debug.log file.

LOGGING = {

'version': 1,
'disable_existing_loggers': False,
'handlers': {
    'file': {
        'level': 'DEBUG',
        'class': 'logging.FileHandler',
        'filename': 'debug.log',
    },
},
'loggers': {
    'django': {
        'handlers': ['file'],
        'level': 'DEBUG',
        'propagate': True,
    },
},
}


import logging
logger = logging.getLogger(__name__)
...... // some code here
    if not data:
        logger.error('Search term is not valid')

The sentence "Search term is not valid" does print out in the console but it is not saved to the debug.log file.

I am not quite sure how Django log works. Is it supposed to behave like that or there is something wrong with my code? Also, how to save the "Search term is not valid" into the debug.log file? Thanks a lot!

Stephan
  • 365
  • 1
  • 5
  • 18

2 Answers2

4

use name that you have given in settings.py, in your case it is django

import logging

# use name that you have given in settings in your case it is  django
logger = logging.getLogger('django')

def my_view(request, arg1, arg):
    ...
    if bad_mojo:
        # Log an error message
        logger.error('Something went wrong!')
Jamil Noyda
  • 3,321
  • 2
  • 21
  • 26
0

try to give full path of the file 'filename': '/path/to/django/debug.log'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/path/to/django/debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

Reference: https://docs.djangoproject.com/en/2.1/topics/logging/#examples

anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62