Receive django error debug report by email : - django

Here is my configuration in django settings :
MAILER_LIST = ['toto#toto.com']
EMAIL_HOST = 'toto.smtp.com'
EMAIL_HOST_USER = 'toto#toto.com'
EMAIL_HOST_PASSWORD = 'tata'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'toto#toto.com'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'DEBUG',
'class': 'django.utils.log.AdminEmailHandler',
'filters': [],
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'DEBUG',
'propagate': True,
},
}
}
i've try to debug with :
from django.core.mail import EmailMessage
email = EmailMessage('Hello', 'World', to=['toto#toto.com'])
email.send()
And i get the test email if i put this in my settings.
i would like to receive this error report by email (it's just an example and i've added this error in my code to test the mail report) :
What am i missing to get the debug log by email ? The test is sending the email so it's not an email configuration problem ...
I would like to get the report by email and still show the debug page on django. And get the email event if debug is true or Not.
So i've set DEBUG = True in my settings.
Thanks and regards

As said in another answers if you want use django build-in AdminEmailHandler, then you need provide ADMINS and MANAGERS instead of MAILER_LIST in your settings.py. Like this:
ADMINS = ['toto#toto.com'] # better to use another mail than EMAIL_HOST_USER
MANAGERS = ADMINS
Django's utils.log have two options for processing your DEBUG value: RequireDebugFalse and RequireDebugTrue.
So if you want send error emails to your admins (ADMINS variable in settings.py) while debug, then you may use similar settings:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue' # log while DEBUG=True
}
},
'handlers': {
'debug_mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'filters': [require_debug_true],
}
},
'loggers': {
'django.request': {
'handlers': ['debug_mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
Upd.:
Also you can use logging.handlers.SMTPHandler. Then you can write something similar to this code: https://code.djangoproject.com/ticket/15917

Django handles this for you, you can add
MANAGERS = ['mail#mail.com']
or look into integrating sentry for a more robust error reporting, sentry is free too

You should use ADMINS:
ADMINS = ['notifications#example.com']
A list of all the people who get code error notifications. When DEBUG=False and AdminEmailHandler is configured in LOGGING (done by default), Django emails these people the details of exceptions raised in the request/response cycle.
More info here

Other than what has already been said in other answers, do not forget to set SERVER_EMAIL in your settings (docs).
It's the email address that error messages come from; it's similar to DEFAULT_FROM_EMAIL but SERVER_EMAIL is used only for error messages. Default value is 'root#localhost' and if you are using a provider like sendgrid your emails will be blocked.

Related

Django.request is not showing synchronous middleware as docs suggest

I've set up a very simple asynchronous view but it's not working. As per the Django instructions I want to check that it's not my middleware causing the issue. The Django docs say that the django.request logger will disclose which middleware is not working in async. Below is the quote from the official docs. I've set up the django.request logger and it logs an 4xx or 5xx errors (as expected) but that's all. Is this a mistake in the Django docs?
https://docs.djangoproject.com/en/4.0/topics/async/
You will only get the benefits of a fully-asynchronous request stack if you have no synchronous middleware loaded into your site. If there is a piece of synchronous middleware, then Django must use a thread per request to safely emulate a synchronous environment for it.
Middleware can be built to support both sync and async contexts. Some of Django’s middleware is built like this, but not all. To see what middleware Django has to adapt, you can turn on debug logging for the django.request logger and look for log messages about “Synchronous middleware … adapted”.
settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'logs/debug.log',
},
},
'root': {
'handlers': ['console'],
'level': 'WARNING',
},
'loggers': {
'django.request': {
#'handlers': ['file','console'],
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}

How configure Django logging to file for app

I am struggling with Django logging configuration. I have one app called "api" and I want to save to file all logs from this app. When I set up a logger to django everything works fine but when I change it to my app_name it doesn't.
Here is my configuration:
File structure:
email_api
api
tasks.py
email_api
celery.py
settings
logs
email.log
My logging configuration:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'logs/email.log',
},
},
'loggers': {
'api': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
tasks.py file where I logging:
import logging
logger = logging.getLogger(__name__)
#app.task(bind=True, default_retry_delay=3, max_retries=3,)
def send_email(self, data, email_id):
message = create_message(data, email)
try:
logger.debug("Log Message Here")
message.send()
Keys in the LOGGING['loggers'][...] dict are names of loggers. You have configured logging with api as a name of the logger.
In order to write to this logger, you should request it by that name:
logger = logging.getLogger('api')
...
logger.debug("Log Message Here")

Django format email django errors

hi i would like create a format for django email errors, the email is automatic send by django in this case get the typical error format:
i would like get in the email report the project name, all type errors(404/500/etc)...
This is my settings:
ADMINS = (
('Diego Avila', 'diego.loachamin#test.com'),
)
#CONFIGURAR PARAMETROS EMAIL
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_SSL = True
EMAIL_HOST = 'mail.test.com'
EMAIL_HOST_USER = 'diego.loachamin#test.com'
EMAIL_HOST_PASSWORD = 'dsdsad'
EMAIL_PORT = 465
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
please someone suggest or idea.. thanks..!!
Django comes with such features built in. For 500 errors, it's a logging handler called AdminEmailHandler. It will trigger when there's uncaught exceptions, and will include the traceback in the email body.
404 is different. That's not an uncaught exception, but you can intercept those with BrokenLinkEmailsMiddleware and send emails.
To customize how these emails look, you can create your own subclass of either or both of AdminEmailHandler and BrokenLinkEmailsMiddleware. Change the relevant logging and middleware config in settings.py to point to your custom logging handler/middleware.
For the logging handler, you can for example use the format_subject method to add something to the subject line of the outgoing email.
class CustomAdminEmailHandler(AdminEmailHandler):
def format_subject(self, subject):
return '[ project name ]' + super().format_subject(subject)
Both the middleware and the logging handler uses django.core.email.mail-admins() to send the emails.

How to setup django logging to console

I know there is a very similar question. That one is six years old and the answer in that one doesn't help me. All I want is to know how to configure django so that it can log to the console.
This are my settings:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
},
},
}
And in my view I have this:
class Home(TemplateView):
template_name = "inicio/magic_py.html"
def get_context_data(self, **kwargs):
logger = logging.getLogger("django")
logger.debug("home!!!!!!")
print("home?")
The console doesn't show the log.debug, it only shows the print. What am I missing? please help.
I use django 1.10
DEBUG log level is lower than INFO so your logs are being filtered out, you'll need to either lower your log level to DEBUG or you need to log using logger.info() or higher.

Use Logging SocketHandler with Django

I've configured my logging as so:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
'cute':{
'class': 'logging.handlers.SocketHandler',
'host': '127.0.0.1',
'port': 19996
},
},
'loggers': {
'django': {
'handlers': ['cute'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
},
},
}
But when I try and log out I get an error in the console:
TypeError: an integer is required (got type socket)
This seems to be happening within an attempt to pickle the log message, I think.
What is going on, and how can I get the SocketHandler to work?
There is a bug report about it. The request object cannot be pickled and the log fails.
My loggers were like yours before I got the same error as you did. Since my code contains apps that don't work with request, I partially fixed my problem creating a log for django.request without socket_handler
'django.request': {
'handlers': ['defaultfile', 'console'],
'level': 'WARNING',
'propagate': False,
},
However the bug report also suggest to create a custom SocketHandler removing request:
from logging.handlers import SocketHandler as _SocketHandler
class DjangoSocketHandler(_SocketHandler):
def emit(self, record):
if hasattr(record, 'request'):
record.request = None
return super().emit(record)
I haven't tried this yet, but it could be a way to go.