Django log errors and traceback in file in production environment

Viewed 457

I'm quite new working with logging in django, I'm making a production deployment (DEBUG=False) of an app but I'm not allowed to use any error tracker like Sentry to catch possible problems, so I was wondering if it's possible to log the traceback or part of it in production environment to a file using a logger.

I made something like this in my production settings:

import logging.config
# Clear prev config
LOGGING_CONFIG = None

# Get loglevel from env
LOGLEVEL = os.getenv('DJANGO_LOGLEVEL', 'debug').upper()

logging.config.dictConfig(
        {
            'version': 1,
            'disable_existing_loggers': False,
            'filters': {
                'require_debug_false': {
                    '()': 'django.utils.log.RequireDebugFalse',
                },
                'require_debug_true': {
                    '()': 'django.utils.log.RequireDebugTrue',
                },
            },

            'handlers': {
                'console': {
                    'level': 'INFO',
                    'filters': ['require_debug_false'],
                    'class': 'logging.StreamHandler',
                },
                'file': {
                    'level': 'DEBUG',
                    'class': 'logging.FileHandler',
                    'filename': 'debug.log',
                },
            },
            'loggers': {
                "": {
                    "level": "ERROR",
                    "handlers": ["console", "file"],
                },

                'django': {
                    'handlers': ['console', 'file'],
                    'level': 'DEBUG',
                    'propagate': True,
                },
                'django.request': {
                    'handlers': ['console', 'file'],
                    'propagate': True,
                    'level': 'ERROR',
                },
            }
        }
    )

But the only thing I got on debug.log is:

Internal Server Error: /job/create/
Internal Server Error: /job/create/
Internal Server Error: /job/create/

Logs to file without any other information, I would like to have some meaningful information in debug.log to have a clue where can be the error, this is something what I would like to get:

[2021-07-27 23:47:29 +0000] [ERROR] Internal Server Error: /job/create/ 
AttributeError
'str' object has no attribute 'strftime'
jobs/views.py in CreateJob at line 29
[2021-07-27 23:49:18 +0000] [ERROR] Internal Server Error: /job/create/ 
AttributeError
'str' object has no attribute 'strftime'
jobs/views.py in CreateJob at line 29

There is a way to achieve that with logging? Or how can I get a traceback or a resume of the traceback in case of possible errors in production environment without services like Sentry?

1 Answers

You can define a logging format and add that to your handler.

For your example this could look like:

'formatters': {
    'mystyle': {
        'format': u'%(asctime)s %(levelname)-6s %(lineno)-4s%(name)-15s %(message)s',
        'datefmt': '%H:%M:%S',
    },
'handlers': {
    'console': {...},
    'file': {
        'level': 'DEBUG',
        'class': 'logging.FileHandler',
        'filename': 'debug.log',
        'format': 'mystyle',
    },
},

The formatter is defined in an own section to make it reusable. I.e. multiple handlers could use the same formatter. A list of what you can use as placeholders in your format can be found here (I think there is something like stack trace as well):

https://docs.python.org/3/library/logging.html#logrecord-attributes

Related