Skip to content

Implement an audit trail application

Gabriele Lucci requested to merge feature/audit-log into master

Implement a Django application which keeps track of additions, changes, and deletions of instances of models.

Specifications

The application should implement the following set of features:

  • Must record all create, update and delete operations done on any instance of certain models.

  • Must record the identifier (or primary key) of the object and its type. (possibly using the contenttypes framework).

  • Must record the date and time on which such operation was performed.

  • Must record the user (an AUTH_USER_MODEL instance) who performed such operation.

The Django admin site's LogEntry model

The Django admin site, has a powerful feature which, apparently, does exactly what we are trying to achieve. Well... kind of. Unfortunately it only does so exclusively for operations on objects performed through the admin interface, while we especially need to keep track of changes done outside of the admin interface (e.g. REST API).

Nevertheless, the LogEntry model could be used as a solid base for our own implementation. We just need to figure out how to hook the creations of new log entries to any front end context, and not just the admin site.

Why not use an existing re-usable app?

The site djangopackages.org has actually a specific grid which lists a comprehensive selection of Django packages that track changes made to instances of models and maintain a log of the changes. Sounds great, right? Why not use one of those packages? Well... not so fast.

While there are some well-made packages, most of them are either too complex, requiring changes to existing Django models, or simply outdated and no longer maintained, and we rather build an app from scratch than trying to figure out how to fix a third-party app.

However, there are some notable packages which could be adopted or at least serve as inspiration for an eventual self-made implementation.

django-easy-audit

Probably the best candidate. The app implements the models CRUDEvent, LoginEvent and RequestEvent, which respectively logs operations done on models, login events (login, logout and even failed attempts) and HTTP requests.

The problem though, is that it logs a little too much (e.g. every single GET request), hitting hard on the database, possibly causing a significant drop in performance. One possible workaround to this, would be to set up a dedicated database for the app's models.

Also, the app can be configured via settings, making possible to specify which models and/or which URLs to log.

Edited by Gabriele Lucci

Merge request reports