In my base.html, I want to render certain menus when a user is on most pages, but there a few where they can't be, so I have something a bit like this:
{% if menu_context %}
<ul class="menu">...</ul>
{% endif %}
This works great, I have a base class for most of my views that adds this variable. The problem is on the pages without it set, I get:
[2016-05-12 13:37:44,819 base] DEBUG: Exception while resolving variable 'menu_context' in template 'index.html'.
Traceback (most recent call last):
File "/.../env/lib/python2.7/site-packages/django/template/base.py", line 905, in _resolve_lookup
(bit, current)) # missing attribute
VariableDoesNotExist: Failed lookup for key [menu_context] in u'[...]'
Is there any way to prevent this from happening?
Alternatively, is there a way to prevent those particular log statements. My logging config is:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'format': '[%(asctime)s %(module)s] %(levelname)s: %(message)s'
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple',
},
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'DEBUG',
},
'django.db.backends': {
'handlers': ['null'], # Quiet by default!
'propagate': False,
'level': 'DEBUG',
},
'django.template.base': {
'handlers': ['null'], # Quiet by default!
'propagate': False,
'level': 'DEBUG',
},
},
}
...but this does not seem to suppress them!
Related
After migrating ids in my Django app from int (default) to UUID4 the admin detail pages are not loading anymore. List views work correctly, also rendering the correct links for the objects:
Link renders as
http://localhost:8000/admin/images/image/27ce8dbc-eb3f-443d-bf04-f612093cdc46/change/
But clicking on the UUID to open the details (or pasting it into a new tab) leads to infinite loading.
Happens for all admins with UUID, the ones with the conventional id work.
Models looks like this:
class Image(models.Model):
"""Uploaded images."""
id = models.UUIDField(primary_key=True, default=uuid4)
# more fields...
Nothing else besides id › uuid4 changed...
Tested in Google Chrome with Django v4.0.7 as well as v4.1.1.
No logs, neither in the browser console nor the Django dev server, just a loading spinner in the browser tab.
Here's the Django logging config:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
},
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
'require_testing_false': {
'()': RequireTestingFalse,
},
},
'handlers': {
'console': {
'level': 'INFO',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
},
'file': {
'level': 'ERROR',
'filters': ['require_debug_false', 'require_testing_false'],
'class': 'logging.FileHandler',
'filename': os.path.join(BASE_DIR, 'logs/django.log'),
},
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false', 'require_testing_false'],
'class': 'django.utils.log.AdminEmailHandler',
},
},
'loggers': {
'django': {
'handlers': [
'console',
],
},
'django.request': {
'handlers': [
'file',
'mail_admins',
],
'level': 'ERROR',
'propagate': False,
},
'django.security': {
'handlers': [
'file',
'mail_admins',
],
'level': 'ERROR',
'propagate': False,
},
'py.warnings': {
'handlers': ['console'],
},
},
}
My Django app is only properly logging and emailing errors when Debug=True.
On production, I'm only getting 'Invalid HTTP_HOST header' errors in both the log file and my inbox. Every other error is not logged in the django log nor is it emailed to me.
I've tried some things with this test request:
def test(request):
logging.debug('debug test message') // Always appears in log file
from django.core.mail import mail_admins
mail_admins('test error', 'test error via call to mail_admins()') // Always arrives in my inbox just fine
raise Appointment.DoesNotExist // When Debug=False (both locally and in production), does not appear in log file or in inbox.
My logging settings for both local and production:
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'
},
'csv_formatter': {
'format': '%(levelname)s;%(asctime)s;%(message)s'
}
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
},
'default': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'maxBytes': 1024 * 1024 * 50,
'backupCount': 10,
'formatter': 'csv_formatter',
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'formatter': 'verbose',
},
},
'loggers': {
'': {
'handlers': ['default'],
'level': 'DEBUG',
'propagate': True,
},
'asyncio': {
'level': 'WARNING',
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'django.security': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
How do I make sure all Django errors are logged and emailed in production (when Debug=False)?
I'm using Django==2.2.11 and djangorestframework==3.11.0.
When I run ./manage.py runserver and make an http request to the endpoint that has some database queries I got all the logging information. This is only when DEBUG = True. If I set DEBUG=False I won't get any logging to console at all:
settings.py:
DEBUG = False
LOGGING = {
'version': 1,
'handlers': {
'console': {
'level': 'DEBUG',
'filters': [],
'class': 'logging.StreamHandler',
}
},
'loggers': {
'django.db.backends': {
'level': 'DEBUG',
'handlers': ['console'],
'propagate': False
},
'django.request': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False
},
}
}
I have a problem related with sending log messages to Sentry server while using Django and Celery async tasks. I utilize Django 1.11, Raven 6.1, Celery 4.0.2.
The log message shows in Sentry server when task is launching synchronous, for example:
#celery.shared_task()
def test_worker():
logger.warning('Logger works!')
raise Exception('---Worker works!')
$ from api.tasks import test_worker
$ test_worker()
When trying launch async task using:
$ res = test_worker.delay()
Sentry server does not contain log about logger.
My settings.py is:
RAVEN_CONFIG = {
'dsn': 'http://my_dsn',
}
SENTRY_AUTO_LOG_STACKS = True
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'root': {
'level': 'DEBUG',
'handlers': ['sentry'],
},
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s - %(message)s'
},
'verbose': {
'format': '%(asctime)s [%(levelname)s] %(module)s:%(funcName)s - %(message)s'
},
},
'handlers': {
# logs directly to Sentry
'sentry': {
'level': 'DEBUG',
'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler',
},
# logs everything to the console
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
},
'loggers': {
'raven': {
'level': 'DEBUG',
'handlers': ['console'],
'propagate': False,
},
'sentry.errors': {
'level': 'DEBUG',
'handlers': ['console'],
'propagate': False,
},
'processing': {
'level': 'DEBUG',
'handlers': ['sentry'],
'propagate': False
},
'celery': {
'level': 'DEBUG',
'handlers': ['sentry'],
'propagate': False
}
},
}
Where I made a mistake, or what I am doing wrong?
Thanks in advance.
I'm trying to setup my logging settings to send logging.info('any message') to a file through stdout.
This is my gunicorn_django script:
$ gunicorn_django -w $NUM_WORKERS --user=$USER --group=$GROUP --log-level=info --log-file=$LOGFILE &>>$LOGFILE
These are my logging settings:
import sys
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'console': {
'level': 'INFO',
'filters': ['require_debug_false'],
'class': 'logging.StreamHandler',
'stream': sys.stdout,
'formatter': 'simple',
},
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'app.location': {
'handlers': ['console'],
'level': 'INFO',
'propagate': False,
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
When I do:
import logging
logging.getLogger('app.location')
logging.info('any message')
It is not logged to the gunicorn_django $LOGFILE. Just print >> sys.stderr messages seem to be showed in the $LOGFILE
How can I log info messages (through stdout) to a file
Your logger is just getting garbage collected as soon as you create it. You need to keep a reference to it as a logger, and then use that logger, like so:
import logging
logger = logging.getLogger('app.location')
logger.info('any message')