8

I can't get logging to work in my Django web app.

My settings file looks like this:

EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 465
EMAIL_HOST_USER = "paulhtremblay@gmail.com"
EMAIL_HOST_PASSWORD = "password"
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = "paulhtremblay@gmail.com"
SERVER_EMAIL = 'smtp.gmail.com'

ADMINS = (
      ('Paul Tremblay', 'paulhtremblay@gmail.com'),
      )

 LOGGING = { 
'version': 1,
'disable_existing_loggers': False,
'handlers': {
    'file': {
        'level': 'ERROR',
        'class': 'logging.FileHandler',
        'filename': '/var/log/django_logs/debug.log'
    },
    'mail_admins': {
     'level': 'ERROR',
       'class': 'django.utils.log.AdminEmailHandler'
               },
},  
'loggers': {
    'django': {
    'handlers': ['file'],
    'level': 'ERROR',
    'propagate': True,
    },
    'django.request': {
    'handlers': ['file'],
    'level': 'ERROR',
    'propagate': True,
    },
},  
 }

I have this in my views file:

 def five_hundred_test(request):
   raise ValueError("raising this on purpose for testing for 500")
   return render(request, 'my_test/basic_css.html')

When I point my browser to this function, I get a 500 Error (as expected), but nothing gets sent to my email, and nothing gets put in the log file. I am using Django 1.9, with python3, using Apache to run the server.

user3520634
  • 301
  • 3
  • 9
  • 1
    If you pasted the code properly, there a space too much before `LOGGING = {`. In any case you should always add the error traceback from the console. – Klaus D. Jul 01 '16 at 02:00
  • I must not have pasted correctly. I see also that there is too much space before "LOGGING". However, the code does not raise any errors (so I can't include the trace). It just doesn't do what it is supposed to. – user3520634 Jul 21 '16 at 01:16
  • You have an error in the environment variables: [SERVER_EMAIL](https://docs.djangoproject.com/en/dev/ref/settings/#server-email) receives an email address. I will update my answer accordingly. – raratiru Sep 09 '16 at 20:47

3 Answers3

9

This can be done much simpler. If you want to log to both to email and Apache log files, you need to do the following in settings.py:

  1. Configure email settings - this assures that Django can send emails

     SERVER_EMAIL = 'me@me.eu'
    
     EMAIL_HOST = 'smtp.me.eu'
     EMAIL_PORT = 587
     EMAIL_USE_TLS = True
     EMAIL_HOST_USER = SERVER_EMAIL
     EMAIL_HOST_PASSWORD = 'password'
    
  2. Set DEBUG to False - this enables error email sending

     DEBUG = False
    
  3. Add error email receivers to ADMINS (you might want MANAGERS, too) - this designates who receives the error emails

     ADMINS = (
       ('Me', 'me@me.eu'),
     )
    
     MANAGERS = ADMINS
    
  4. Finally, remove the default console filter that does not let messages through when debug mode is disabled - this enables errors to end up in Apache error logs

     from django.utils.log import DEFAULT_LOGGING
    
     # Assure that errors end up to Apache error logs via console output
     # when debug mode is disabled
     DEFAULT_LOGGING['handlers']['console']['filters'] = []
    

    This has to be in settings.py as logging will be configured with DEFAULT_LOGGING immediately after settings have been imported.

In case you want to add support for logging from your own code, configure the root logger in settings.py as well:

# Enable logging to console from our modules by configuring the root logger
DEFAULT_LOGGING['loggers'][''] = {
    'handlers': ['console'],
    'level': 'INFO',
    'propagate': True
}

Finally, you may want to turn on detailed logging:

# Detailed log formatter
DEFAULT_LOGGING['formatters']['detailed'] = {
    'format': '{levelname} {asctime} {pathname}:{funcName}:{lineno} {message}',
    'style': '{',
}
DEFAULT_LOGGING['handlers']['console']['formatter'] = 'detailed'

You can then use it as follows:

log = logging.getLogger(__name__)
log.info('Logging works!')
mrts
  • 16,697
  • 8
  • 89
  • 72
8

This is my working setup. I have not added a console logger, as I am using it only to production. The inspiration came from the relevant Logging Examples of Django docs.

Here are my email and logging settings and here is a link to the relevant django docs for the email backend:

from os.path import join

# Email Configuration ==========================================================
ADMINS = [('Me', 'my@email'), ]
MANAGERS = ADMINS
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = 'My Name To Display <my@email>'
SERVER_EMAIL = 'error_from@email'
EMAIL_HOST = 'smtp.server'  # An IP may work better
EMAIL_HOST_USER = 'username_for_login'
EMAIL_HOST_PASSWORD = 'password_for_login'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

# Logging Configuration ========================================================
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'file': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': join(HOME_DIR, 'my_logs', 'debug.log'),
            'formatter': 'verbose'
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'formatter': 'simple'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'ERROR',
            'propagate': True,
        },
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    },
}

I have spotted two errors to your environment variables:

  • The SERVER_EMAIL setting must be be an email address.
  • You are using TLS and therefore the correct port should be 587.

Moreover, you are trying to use Google as an SMTP server, but according to this updated answer this service is no longer available from google and you have to search for another SMTP server.

I have also assembled a post with a couple debugging techniques if you need to use.

raratiru
  • 8,748
  • 4
  • 73
  • 113
1

Also check your email client rules on what to do with the emails once they arrive.

I had some rules in my e-mail client with errors and they were stopping my Django logging mails to enter/show up.